Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple way for QuerySet union and subtraction in django?

Tags:

Consider two QuerySet objects of the same class. Is there a simple way to unify them into a single QuerySet by calculating the union? Also, is there a simple way to subtract them? Removing all elements that appear in both sets from one of the sets?

like image 331
Jonathan Livni Avatar asked Jun 04 '10 13:06

Jonathan Livni


People also ask

What is Union in Django?

The UNION operator is used to combine the result-set of two or more querysets. The querysets can be from the same or from different models. When they querysets are from different models, the fields and their datatypes should match.

How do I do a not equal in Django QuerySet filtering?

To do a not equal in Python Django queryset filtering, we can negate a equal with ~ . to call filter with the Q object negated with ~ to return all the Entry results that don't have id 3.

What is QuerySet in Django with example?

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

Since Django 1.11, QuerySets have union(), intersection() and difference() methods.

It's also possible to use & and | operators with QuerySets (I could not find a reference to this in the docs, so I guess union() and intersection() is the preferred way to combine two querysets.

qs3 = qs1.union(qs2)         # or qs3 = qs1 | qs2 qs3 = qs1.intersection(qs2)  # or qs3 = qs1 & qs2 qs3 = qs1.difference(qs2)    # the ^ operator is not implemented. 

You can also use Q() objects which like QuerySets implement | and &, and additionally the inversion operator ~

like image 158
Håken Lid Avatar answered Sep 30 '22 23:09

Håken Lid


Subtract a QuerySet from another QuerySet using the same model.

This works - but is probably slowly

queryset_with_hello = Blog.objects.filter(name__icontains='hello') queryset_without_hello = Blog.objects.exclude(pk__in=queryset_with_hello) 

Read the performance considerations in django documentation:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#in

like image 43
Demokrates Avatar answered Sep 30 '22 23:09

Demokrates