Annotating a Django queryset with a left outer join?

前端 未结 10 724
予麋鹿
予麋鹿 2020-12-14 01:06

Say I have a model:

class Foo(models.Model):
    ...

and another model that basically gives per-user information about Foo:

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 01:46

    A solution with raw might look like

    foos = Foo.objects.raw("SELECT foo.* FROM foo LEFT OUTER JOIN userfoo ON (foo.id = userfoo.foo_id AND foo.user_id = %s)", [request.user.id])
    

    You'll need to modify the SELECT to include extra fields from userfoo which will be annotated to the resulting Foo instances in the queryset.

提交回复
热议问题