Django in / not in query
Django uses __in
lookup to filter model instances based on whether a field's value is IN or NOT IN a list. To get matches, Django uses filter
. To omit these values, Django uses exclude
.
Here’s a common usage:
- The
__in
syntax is compatible with any iterable (lists, tuples, querysets). - Please use
YourModel
in the place of your model. - Kindly insert
field
and[values]
with your field name and the values to match or exclude.
Using subqueries to exclude
If curtailing certain records from your condition based on another table, here's a solid move with Django for a 'not in' query:
Extra gifts:
- The
your_condition
filters data inTable2
. exclude
denies the records inTable1
whereid
features inleave_out_ids
.- The
flat=True
makes sure the list of IDs is one-level and not a list of tuples.
Handling related models
In a scenario with ForeignKey relations:
Here, we're snubbing items where the related model has a field on par with the specified value
.
Complex queries with Q objects
Rummaging through complex questions? Q objects they're your rescue rope:
- The
~
acts as a magic wand & negates the Q object. - Did I say you can store these Q objects in variables to dust off any redundancy?
Custom SQL and performance pointers
Write your custom SQL into the queries with objects.extra()
. The control is all yours:
Worthy to keep in mind:
- It's robust but don't forget you're in the ring with SQL injection risks.
- Keep your SQL efficient to uphold good performance.
Different situations and their solutions
Large list of values? Not a problem!
For a large list of values, using __in
with a list input can get hefty:
A subquery might serve here:
Not IN with NULL values? Here's the catch!
NULL values can toss a wrench in NOT IN
logic of SQL because a NULL
understands nothing equal to it:
Instead, use two conditions—one to exclude and another to check for NULL:
Baking 'not in' logic
For custom 'not in' logic, you can turn a head with custom lookups:
Remember to keep your lookups organized with a clear handle on code readability and performance.
Was this article helpful?