zoukankan      html  css  js  c++  java
  • ORM之查询

    一、对象查询

    1、正向查询

        ret1=models.Book.objects.first()
        print(ret1.title)
        print(ret1.price)
        print(ret1.publisher)
        print(ret1.publisher.name)  #因为一对多的关系所以ret1.publisher是一个对象,而不是一个queryset集合

     2、反向查询

        ret2=models.Publish.objects.last()
        print(ret2.name)
        print(ret2.city)
        #如何拿到与它绑定的Book对象呢?
        print(ret2.book_set.all())   #ret2.book_set是一个queryset集合

    二、(__)单表条件条件查询

        models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值
        models.Tb1.objects.filter(id__in=[11, 22, 33])   # 获取id等于11、22、33的数据
        models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in
        models.Tb1.objects.filter(name__contains="ven")
        models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
        models.Tb1.objects.filter(id__range=[1, 2])     # 范围bettwen and
        startswith,istartswith, endswith, iendswith
     

    三、(__)多表条件关联查询

    1、正向查找(条件)

    1.1 一对一查询

        ret3=models.Book.objects.filter(title='Python').values('id')
        print(ret3)        #[{'id': 1}]

    1.2 一对多查询

        ret4=models.Book.objects.filter(title='Python').values('publisher__city')
        print(ret4)        #[{'publisher__city': '北京'}]

    1.3 多对多查询

        ret5=models.Book.objects.filter(title='Python').values('author__name')
        print(ret5)
        ret6=models.Book.objects.filter(author__name="alex").values('title')
        print(ret6)
        #注意
        #正向查找的publisher__city或者author__name中的publisher,author是book表中绑定的字段
        #一对多和多对多在这里用法没区别

    2、反向查询(条件)

    2.1 一对多查询

        ret8=models.Publisher.objects.filter(book__title='Python').values('name')
        print(ret8)  #[{'name': '人大出版社'}]  注意,book__title中的book就是Publisher的关联表名
    
        ret9=models.Publisher.objects.filter(book__title='Python').values('book__authors')
        print(ret9)  #[{'book__authors': 1}, {'book__authors': 2}]

    2.2 多对多查询

        ret10=models.Author.objects.filter(book__title='Python').values('name')
        print(ret10)  #[{'name': 'alex'}, {'name': 'alvin'}]
    
        #注意
        #正向查找的book__title中的book是表名Book
        #一对多和多对多在这里用法没区别

    注意:条件查询即与对象查询对应,是指在filter,values等方法中的通过__来明确查询条件。

  • 相关阅读:
    python初学第一节课
    关于float类型和u32类型问题
    今天的工作状态,规划未来一段时间内必须完成的事情(Record the working status of today,planning for the next period of time must be completed)
    STM32 硬件I2C初始化 I2C1_GPIO_AF_Config
    C语言编程规范--------12 宏
    C语言编程规范--------11 代码测试、维护
    C语言编程规范--------10 代码编辑、编译、审查
    C语言编程规范--------9 质量保证
    C语言编程规范--------8 效率
    C语言编程规范--------7 可测性
  • 原文地址:https://www.cnblogs.com/cainingning/p/10060048.html
Copyright © 2011-2022 走看看