用布尔值注释查询集,其中一个字段等于或不等于另一个字段

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

问题是关于 Django 中的注释。

例如我有以下模型:

class Example(models.Model):

    field_1 = PositiveIntegerField()
    field_2 = PositiveIntegerField()

而且我想根据 field_1 == field_2

是否使用布尔值 TrueFalse 注释基于此模型的查询集

我设法找到了 2 个解决方案,这两个都不让我满意。

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

使用 Raw SQL,extra() 即将弃用。

2)

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

这非常冗长,使查询集慢了 4 倍。

问题是 - 是否可以在 Django ORM 中表达这样的逻辑而不使用 RAW SQL 并且逻辑更简洁更直接?

谢谢。

在 Whosebug 上找到这个。

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