Assuming that field is nullable, in raw SQL condition
WHERE field <> 1
will exclude all 1 rows and also exclude all NULL rows.
Why Django ~Q(field=1) makes query
WHERE (NOT (field = 1 AND field IS NOT NULL))
which results to include NULL rows. Is there equivalent for SQL field <> 1 in Django ORM?
Because Django's interpretation makes more sense from a Python developer's point of view. SQL has separate constructs for checking for null values (
IS NULLandIS NOT NULL), and bothfield == NULLandfield <> NULLareNULL(neithertruenorfalse), which is not exactly intuitive.Think of it this way: If I want to get all rows where
field <> 1I probably want to get rows withNULLvalues as well becauseNULLis not1.If you want to replicate the same behaviour you can use something like