如何获取Queryset中所有对象的所有ForeignKeys的Django QuerySet [英] How to get a django QuerySet of all ForeignKeys of all objects in a Queryset

查看:145
本文介绍了如何获取Queryset中所有对象的所有ForeignKeys的Django QuerySet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型(或实际上有2个模型,但其他模型并不相关)

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

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

当我有一个 Foo :s的QuerySet时,如何获得所有 Bar 那个QuerySet引用的实例?

When I have a QuerySet of Foo:s, how do I get all the Bar instances that are referenced by that QuerySet?

由于我使用的是MySQL,因此我无法执行 .distinct( ['bar'])

Since I'm using MySQL, I can't do .distinct(['bar'])

推荐答案

foo_queryset = Foo.objects.filter(attr=value)
referenced_bars = Bar.objects.filter(id__in=foo_queryset.values('bar_id'))

这篇关于如何获取Queryset中所有对象的所有ForeignKeys的Django QuerySet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆