Annotate queryset with boolean where one field is equal or not to another field

Viewed 247

The question is regarding annotation in Django.

For example I have a following model:

class Example(models.Model):

    field_1 = PositiveIntegerField()
    field_2 = PositiveIntegerField()

And I want to annotate queryset based on this model with boolean True or False based on whether field_1 == field_2

I managed to find 2 solutions on this, both of that don't satisfy me.

  1. Example.objects.extra(select={'equal': r' field_1 = field_2'})

Use Raw SQL, and extra() that is about to get deprecated.

2)

Example.objects.all()\
    .annotate(
    equal=
        Case(
            When(field_1=F('field_2'), then=True),
            default=False,
            output_field=BooleanField(),
        )
    )

Which is quite verbose and makes queryset 4 times slower.

Question is - is it possible to express such logic in Django ORM without the usage of RAW SQL and with less verbose and more straightforward logic?

Thank you.

1 Answers

Found this one here on Stackowerflow.

annotate(
            equal=ExpressionWrapper(
                Q(field_1=F('field_2')),
                output_field=BooleanField()
            ))
Related