Annotating a Django queryset with a left outer join?

前端 未结 10 751
予麋鹿
予麋鹿 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:45

    You could do this using simonw's django-queryset-transform to avoid hard-coding a raw SQL query - the code would look something like this:

    def userfoo_retriever(qs):
        userfoos = dict((i.pk, i) for i in UserFoo.objects.filter(foo__in=qs))
        for i in qs:
            i.userfoo = userfoos.get(i.pk, None)
    
    for foo in Foo.objects.filter(…).tranform(userfoo_retriever):
        print foo.userfoo
    

    This approach has been quite successful for this need and to efficiently retrieve M2M values; your query count won't be quite as low but on certain databases (cough MySQL cough) doing two simpler queries can often be faster than one with complex JOINs and many of the cases where I've most needed it had additional complexity which would have been even harder to hack into an ORM expression.

提交回复
热议问题