如何在django queryset中执行或条件?

时间:2022-05-16 15:21:41

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

我想编写一个与这个SQL查询等价的Django查询:

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

How to construct the Djagno queryset filter?

如何构造Djagno queryset过滤器?

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

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

这不起作用,因为它和过滤器有关。我想要或过滤器获得单个查询集的联合。

2 个解决方案

#1


392  

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

via Documentation

通过文档

#2


40  

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.

因为QuerySets实现了Python __or__操作符(|)或union,所以它就可以工作了。正如您所期望的,|二进制操作符返回一个QuerySet,以便可以将order_by()、.distinct()和其他QuerySet过滤器附加到末尾。

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')

#1


392  

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

via Documentation

通过文档

#2


40  

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.

因为QuerySets实现了Python __or__操作符(|)或union,所以它就可以工作了。正如您所期望的,|二进制操作符返回一个QuerySet,以便可以将order_by()、.distinct()和其他QuerySet过滤器附加到末尾。

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')