过滤后如何获取单个相关对象

时间:2013-05-14 13:15:00

标签: python django django-orm django-filter

我有亲子(1-n)模型关系:

class Parent(models.Model):
    some_fields = models.IntegerField()

class Child(models.Model):
    parent = models.ForeignKey(Parent, relatend_name='children')
    first = models.BooleanField()
    second = models.BooleanField()

现在我根据子字段过滤父母:

Parent.objects.filter(children__first=True)

这将生成以下SQL:

SELECT app_parent.*
FROM app_parent
INNER JOIN app_child ON app_parent.id = app_child.parent_id 
WHERE app_child.first = TRUE

之后我获得了所有父字段但是我希望相关的子字段也能像这样得到SQL:

SELECT app_parent.*, app_child.*
FROM app_parent
INNER JOIN app_child ON app_parent.id = app_child.parent_id 
WHERE app_child.first = TRUE

通过Django ORM获取它。有什么想法吗?

更新

我认为我有很好的解决方法

parents = Parent.objects.filter(children__first=True).prefetch_related('children') \
.extra(select={'child_id': '"app_child"."id"'})
for parent in parents:
    parent.child = [child for child in parent.children.all() if child == parent.child_id][0]

2 个答案:

答案 0 :(得分:1)

您可以使用prefetch_related

Parent.objects.filter(children__first=True).prefetch_related('children')

select_related

Child.objects.filter(first=True).select_related('parent')

答案 1 :(得分:0)

你必须使用fetch_related方法,不幸的是以相反的方式进行查找。

在这种情况下,它应该是这样的:

first_children = Child.objects.filter(first=True).select_related('parent')
parents = [c.parent for c in first_children]