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!
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.
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.
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.
In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.
A.exclude(pk__in = B)
should work
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With