假设我有以下型号:
class ParentModel(models.Model):
name = models.CharField()
child = models.ForeignKey("ChildModel")
class ChildModel(models.Model):
name = models.CharField()
现在,鉴于ParentModels上的一些过滤器,我想检索所有子模型的列表。我试过了:
children = ParentModel.objects.filter(name__startswith='A').values_list('child', flat=True)
但是,这将返回ChildModel ID列表,而不是完整对象。是否有一个queryset函数可以完成我想要做的事情或者我需要使用返回的id编写额外的过滤器查询? I.e.-而不是:
children => [51L, 53L, 54L]
我想:
children => [<ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>]
答案 0 :(得分:3)
您可以将子查询与__in
:
Child.objects.filter(parent__in=Parent.objects.filter(name__startswith='A'))
(注意,你的命名在这里有点奇怪:通常孩子是带有外键的孩子,因为它假设父母可以有多个孩子。)
答案 1 :(得分:1)
我认为您可能希望将模型重构为:
class ParentModel(models.Model):
name = models.CharField()
class ChildModel(models.Model):
name = models.CharField()
parent = models.ForeignKey(ParentModel)
然后,您可以执行以下操作以接收ChildModel
:
ParentModel.childmodel_set.all()
这将被解释为“每个ParentModel可以有许多ChildModel。”
答案 2 :(得分:1)
这是Django网站上的一个活跃问题: https://code.djangoproject.com/ticket/8144
您有两种选择:
我知道如何实施选项2,所以这是我的方法:
选项#2:
<%= link_to 'Enquire about this Service', new_service_enquire_path(@service),
class: "btn btn-primary enquire-btn text-middle" %>