Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one find the entities in a Django query set that are not in another specified query set?

I am using Django to develop a course registration site for an educational institution.

Suppose I have two Django query sets, one that comprises of courses that occupy session 1 (set A) and one that comprises of courses in session 2 (set B):

A = session1.courses.all()
B = session2.courses.all()

There is much overlap between these two query sets.

What is an efficient way to obtain the set of courses within set B, but not in set A?

I believe this is equivalent to taking out the intersection of the two sets from set B.

Thank you!

like image 272
dangerChihuahua007 Avatar asked Jan 15 '12 05:01

dangerChihuahua007


People also ask

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

To answer your specific question, there is no "not equal to" but that's probably because django has both "filter" and "exclude" methods available so you can always just switch the logic round to get the desired result.

What does .all do in Django?

Definition of the all() manager method: all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.

What does _SET do in Django?

The _set is a reverse lookup class variable django puts in for you. The reason the reverse is a queryset is, ForeignKey is 1-to-many relationship. Hence, the reverse is a queryset. The _set object is made available when related_name is not specified.

What is F in Django QuerySet?

In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.


2 Answers

A.exclude(pk__in = B) should work

like image 176
Marcin Avatar answered Oct 24 '22 06:10

Marcin


Starting from version 1.11, django query sets have a builtin difference method.

   C = A.difference(B) #A-B

See my blog post on this for more detailed use cases.

like image 34
Jose Cherian Avatar answered Oct 24 '22 08:10

Jose Cherian