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等方法中的通过__来明确查询条件。  

  

  

  

  

  

  

  

原文地址:https://www.cnblogs.com/xihuanniya/p/10060380.html