Django left outer join with filter

前端 未结 1 512

I\'m using Django\'s built-in user model and have a custom Foo object with a ForeignKey to User. I\'m looking to select all User objects and all of the Foo objects that fit cert

相关标签:
1条回答
  • 2021-02-05 21:55

    If you wanted Django to fetch all the User objects and all the Foo objects that are related to a user object, then you'd use select_related():

    User.objects.all().select_related('foo')
    

    but here you don't want all the Foo objects that are related to a user object, you just want the subset of them that satisfy your criteria. I don't know of a way to tell Django to do that in a single query set. But what you can do is to do both selects separately and do the join in Python:

    # Map from user id to corresponding Foo satisfying <criteria>, if any.
    foos = {foo.user_id: foo for foo in 
            Foo.objects.filter(user__isnull = False, <criteria>)}
    for user in User.objects.all():
        foo = foos.get(user.id)
        # ...
    

    (This doesn't do any more database work or transfer any more data than your LEFT OUTER JOIN would, so I think it's a reasonable approach.)

    0 讨论(0)
提交回复
热议问题