型号:
class Bar(GenericModel):
...
class Foo(GenericModel):
bar = models.ForeignKey(Bar, related_name='foo_bar')
查询:
bars = Bar.objects
.prefetch_related('foo_bar')
.annotate(sum_foo=Sum(
Case(
When(foo_bar__is_deleted=False, then='foo_bar__amount'),
default=Value(0),
output_field=IntegerField()
)
)
)
前者导致内部连接:SELECT ... FROM "bar" INNER JOIN "foo" ON ( "bar"."id" = "foo"."bar_id" ) ...
我打算获得的是 LEFT OUTER JOIN(用“foo.amount”总和注释的“bar”对象的完整列表,如果与“bar”相关的“foo”不存在,则为 0)而不是 INNER JOIN?是否可以不回退到原始 SQL?