Django在BooleanField上注释 [英] Django annotate on BooleanField
问题描述
我有以下模型:
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo)
is_successful = models.BooleanField()
我想获取所有 foo
对象,如果所有 bar <与
foo
对象关联的/ code>对象的 is_successful
为 True
I would like to get all foo
objects with an annotation if all of the bar
objects associated with foo
object have is_successful
as True
到目前为止,我的查询集是:
So far my queryset is:
foos = Foo.objects.all().annotate(all_successful=Min('bar__is_successful'))
The all_successful
批注的想法是,如果所有 is_successful
行的最小值为1,则所有行必须为 True
(假设 0
是 False
和 1
是 True
)。所以知道我可以这样使用查询集:
The idea for the all_successful
annotation is that if the minimum value of all is_successful
rows is 1, then all of them must be True
(assuming 0
is False
and 1
is True
). So knowing that I can use the queryset like so:
foo = foos[0]
if foo.all_successful == 1:
print 'All bars are successful'
else:
print 'Not all bars are successful'
这在sqlite中效果很好,但在PostgreSQL中失败,因为PostgreSQL无法在布尔列上执行 MIN
聚合。我猜这在sqlite中行得通,因为sqlite将布尔值视为整数,因此它可以执行聚合。
This works great in sqlite however it fails in PostgreSQL because PostgreSQL can't execute MIN
aggregate on a boolean column. I guess this works in sqlite because sqlite treats bools as integers hence it can execute the aggregate.
我的问题是如何在不转换是否成功
字段到 IntegerField
?
My question is how can I make this queryset work in PostgreSQL without converting my is_successful
field to an IntegerField
?
感谢
推荐答案
我知道这是一个老问题,但是最近我遇到了这个问题。 Django v1.8现在已经内置了对case / when的支持,因此您可以使用ORM而不是使用自定义SQL进行修改。
I know this is an old question, but I ran up against this recently. Django v1.8 now has built in support for case/when, so you can use the ORM instead of hacking around with custom SQL.
https://docs.djangoproject.com/zh-CN/1.8/ref/models/conditional-表达式/#case
Foo.objects.annotate(
all_successful=Case(
When(bar__is_successful=False, then=False),
When(bar__is_successful=True, then=True),
default=False,
output_field=BooleanField()
))
我还没有尝试过,但是在最近的一个项目中,类似的东西对我有用。
I haven't tried this out, but something similar worked for me on a recent project.
这篇关于Django在BooleanField上注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!