【问题标题】:Annotate queryset with boolean where one field is equal or not to another field用布尔值注释查询集,其中一个字段等于或不等于另一字段
【发布时间】:2020-10-31 08:01:58
【问题描述】:

问题是关于 Django 中的注释。

例如我有以下模型:

class Example(models.Model):

    field_1 = PositiveIntegerField()
    field_2 = PositiveIntegerField()

并且我想根据 field_1 == field_2 是否使用布尔值 TrueFalse 来注释基于此模型的查询集

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

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

使用原始 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 并且使用更少冗长和更直接的逻辑?

谢谢。

【问题讨论】:

标签: django django-orm


【解决方案1】:

在 Stackowerflow 上找到了这个。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2022-08-05
    • 2020-07-06
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多