Why no query expression for equality checks?

I fear my question might sound naive, but here goes.

Using Equals, a query expression I just made up which checks for equality, I can write queries like this one:

foos = Foo.objects.annotate(
    qux=Case(When(Equals(F("bar") * F("baz"), Value(2)), then="yes"), default="no"),
).all()

Yet there is no query expression resembling Equals in Django, and I need to find other ways to write my queries.

I am aware that I can put my calculation in an annotation and check its result, but ultimately I feel a loss of readability compared to simply using Equals if it existed.

Am I the only one thinking this? Would Django benefit from the inclusion of something like Equals? Is there an argument against its inclusion that I missed?

(I’d be happy to contribute the code necessary to make Equals happen, depending on the replies I get!)

Yet there is no query expression resembling Equals in Django, and I need to find other ways to write my queries.

Lookups are not currently usable as conditional expressions but assuming they were you could use django.db.models.lookups.Exact for this purpose

1 Like

@juliencampion you might be happy to learn that @Ian-Foote is working on this exact feature Fixed #27021 -- Support annotating lookups by Ian-Foote · Pull Request #14494 · django/django · GitHub

That is a pleasant surprise! I can even see that in the added unit tests, django.db.models.lookups.Exact is used in the exact way you said it could. That will make my code snippet possible to write!

Thanks a lot to both of you!