django 查询如何使用 or

参考:http://stackoverflow.com/questions/6567831/how-to-perform-or-condition-in-django-querysetpython

django自带的orm,虽然给咱们写代码带来了方便,可是因为自己的一些限制,有些复杂的sql查询语句没办法时间,今天就说一下django  orm中的  或者 查询。sql

SELECT * from user where income >= 5000 or income is NULL.

  上面的sql语句咱们查询收入大于5000或者收入 为空的记录。下面介绍两种方法实现  or  查询django

第一种方法:使用 Q查询code

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

 

第二种方法:使用 管道符号  | ,orm

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')                                                    
相关文章
相关标签/搜索