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