How to perform OR condition in django queryset?

I want to write a Django query equivalent to this SQL query:

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

How to construct the Djagno queryset filter?

User.objects.filter(income__gte=5000, income=0)

This doesn't work, because it AND s the filters. I want to OR the filters to get union of individual querysets.


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

通过文档


Because QuerySets implement the Python __or__ operator ( | ), or union, it just works. As you'd expect, the | binary operator returns a QuerySet so order_by() , .distinct() , and other queryset filters can be tacked on to the end.

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')
链接地址: http://www.djcxy.com/p/76436.html

上一篇: 如何确定类型在C ++ 03中是否可引用?

下一篇: 如何在django queryset中执行OR条件?