How to get a django QuerySet of all ForeignKeys of all objects in a Queryset

前端 未结 3 1643
温柔的废话
温柔的废话 2021-02-03 12:27

I have a model (or actually 2 models, but the other is not that relevant)

class Foo(models.Model):
    ...
    bar = models.ForeignKey(Bar,
        ...
    )


        
相关标签:
3条回答
  • 2021-02-03 12:45

    you could use foo_queryset.bar_set.all() to get all instances of your Bar

    foo_queryset = Foo.objects.filter(attr=value)
    referenced_bars = foo_queryset.bar_set.all()
    

    The Django documentation has more details.

    0 讨论(0)
  • 2021-02-03 12:55
    foo_queryset = Foo.objects.filter(attr=value)
    referenced_bars = Bar.objects.filter(id__in=foo_queryset.values('bar_id'))
    
    0 讨论(0)
  • 2021-02-03 12:56
    bars = Bar.objects.filter(foo_set__attr=value)
    
    0 讨论(0)
提交回复
热议问题