Django-获取外键对象列表 [英] Django- getting a list of foreign key objects

查看:285
本文介绍了Django-获取外键对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下模型:

Lets say I have the following models:

class ParentModel(models.Model):
    name = models.CharField()
    child = models.ForeignKey("ChildModel")

class ChildModel(models.Model):
    name = models.CharField()

现在,鉴于ParentModels上的某些过滤器,我想检索所有子模型的列表。我试过了:

Now, given some filter on ParentModels, I want to retrieve a list of all children models. I have tried:

children = ParentModel.objects.filter(name__startswith='A').values_list('child', flat=True)

但是这将返回ChildModel id的列表,而不是完整的对象。是否有一个queryset函数可以完成我想做的事情,还是需要使用返回的ID编写其他过滤器查询?即-而不是:

However this returns a list of ChildModel ids, rather than the full objects. Is there a queryset function that will accomplish what I am trying to do or do I need to write an additional filter query using the returned ids? I.e.- instead of:

children => [51L, 53L, 54L]

我要:

children => [<ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>]


推荐答案

您可以在 __ in 中使用子查询:

You can use a subquery with __in:

Child.objects.filter(parent__in=Parent.objects.filter(name__startswith='A'))

(请注意,您的命名在这里有点奇怪:通常,孩子是具有外键的孩子,因为它假定父母可以有多个孩子。)

(Note, your naming is a bit odd here: usually the child is the one with the foreign key, since it assumes that a parent can have multiple children.)

这篇关于Django-获取外键对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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