0

我得到了父子(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]
4

2 回答 2

1

您可以使用prefetch_related

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

或者select_related

Child.objects.filter(first=True).select_related('parent')
于 2013-05-14T13:26:07.143 回答
0

您必须为此使用fetch_related方法并不幸地以相反的方式进行查找。

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

first_children = Child.objects.filter(first=True).select_related('parent')
parents = [c.parent for c in first_children]
于 2013-05-14T13:23:28.453 回答