Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Django queryset filter?

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.

like image 587
Elisa Avatar asked Jul 04 '11 06:07

Elisa


People also ask

How does QuerySet work in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

Is Django QuerySet lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.


2 Answers

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

via Documentation

like image 196
lprsd Avatar answered Oct 07 '22 01:10

lprsd


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') 

Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.

like image 23
hobs Avatar answered Oct 07 '22 00:10

hobs