#34959: Q(a=b) and Exact(a, b) handle NULLs differently
-------------------------------------+-------------------------------------
Reporter: Roman | Owner: nobody
Odaisky |
Type: Bug | Status: new
Component: Database | Version: 5.0
layer (models, ORM) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
||= Expression =||= SQL =||
|| Q(f=42) || m.f = 42 ||
|| ~Q(f=42) || NOT(m.f = 42 AND m.f IS NOT NULL) ||
|| Exact(F("f"), 42) || m.f = (42) ||
|| ~Exact(F("f"), 42) || NOT m.f = (42) ||
~Q tries to treat SQL NULLs like Python None values, ~Exact doesn’t, so Q
| ~Q covers the entire table while Exact | ~Exact omits the null values.
Given that people who need to use lookups, F objects, functions and so on
are most likely doing something complex, I doubt it’s advisable or even
possible to extend the null-as-None behavior to every possible expression
(the `in` lookup doesn’t try to do that, for example). But in this case
the documentation should be very clear that the discrepancy exists and Q
objects do extra magic that the lookups do not.
Another option is to deprecate the `~` operator on anything but Q objects,
and force people to use `NegatedExpression` (hopefully aliased to `Not`)
so it’s explicit it doesn’t do the same thing as ~Q.
By the way, the magic can easily backfire with custom lookups:
{{{
def lookupify(function):
class LookupifyLookup(Lookup):
prepare_rhs = False
def as_sql(self, compiler, connection):
return compiler.compile(
function(self.lhs, self.rhs)
.resolve_expression(compiler.query)
)
return LookupifyLookup
Field.register_lookup(
lookupify(
lambda x, y: Exact(Exact(x, 0) | IsNull(x, True), y),
),
"isblank",
)
SomeModel.objects.exclude(field__isblank=True)
# will exclude zeroes but not nulls!
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/34959>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/0107018bb1db5eb3-10297c6c-45e6-43c2-9054-5e761572cade-000000%40eu-central-1.amazonses.com.