…and the rest of comparison operators (<, <=, >=, ==).
The Combinable class
Provide[s] the ability to combine one or two objects with some connector. For example F(‘foo’) + F(‘bar’).
However, it currently only allows arithmetic operators( + - * / ^ %) and bitwise operators (& | << >> #). Some people have expressed the desire to allow boolean comparison in here. There are workarounds to this, but they’re not neat (a. using ExpressionWrapper, b. using Case and When).
There is a small disadvantage that we have to declare the output field as a BooleanField, but we can include that in the code.
you could do it with what arguably is an extra step but …?
queryset.annotate(
expectation=Value(10), # or actual field value
reality=Value(5), # or actual field value
is_happy=Case(
When(
expectation__gt=F('reality'),
then=Value(True),
),
default=Value(False),
output_field=models.BooleanField()
)
)
Yes of course it’s possible but it looks a bit awkward. I was just wondering why they never put boolean comparisons in the first place since they’re so easy to implement. The only reason I can think of is that we’d have to place it on an expression wrapper to set the output field to boolean, which I did in my code. Is there any other reason not to have them?
In addition to being awkward it prevents from creating reusable expressions that you don’t want to have to set up in an annotate function.
For Example:
I use this all over my code. so it would be very messy to have to set up field_or_expr each time in annotate. Instead I had to create the GreaterThan func:
If I wanted to push this forwards, I’d wrap that in a little packages, open a proof-of-concept PR, with tests, and simple docs and put it on PyPI. It should be quite easy to get community feedback at that point.
(Update: It’s needs to be an edit to the existing class… )