在Django中,从查询相关模型和子模型创建嵌套数据字典的最有效方法是什么?
例如,如果我有以下型号:
我已经看过django的model_to_dict方法了,这非常酷,所以我想我可以循环遍历每个级别的查询集并创建一堆数据库对每个实例调用每个级别,但是有更好的方法吗?
例如,可以" prefetch_related"用于获取所有三层,因为它用于获得两层here?
让字典看起来像这样很好:
[
{
"name": "Peter Parent",
"children": [
{
"name": "Chaden Child",
"pets": [
{
"name": "Fanny",
"type:": "fish"
},
{
"name": "Buster",
"type:": "bunny"
}
]
},
{
"name": "Charlete Child",
"pets": [
{
"name": "Dandy",
"type:": "dog"
}
]
}
]
}
]
根据要求,这就是模型的样子:
class Pet(models.Model):
name = models.CharField(max_length=50)
type = models.CharField(max_length=50)
def __str__(self):
return self.name
class Child(models.Model):
name = models.CharField(max_length=50)
pets = models.ManyToManyField(Pet)
def __str__(self):
return self.name
class Parent(models.Model):
name = models.CharField(max_length=50)
children = models.ManyToManyField(Child)
def __str__(self):
return self.name
这就是原始sql的样子:
SELECT pa.name, ch.name, pe.name, pe.type
FROM aarc_parent pa
JOIN aarc_parent_children pc ON pc.parent_id = pa.id
JOIN aarc_child ch ON ch.id = pc.child_id
JOIN aarc_child_pets cp ON cp.child_id = ch.id
JOIN aarc_pet pe ON pe.id = cp.pet_id
答案 0 :(得分:1)
您可以使用prefetch_related
以及列表推导。每次访问相关对象时,prefetch_related
都有助于避免额外的查询。
parents = Parent.objects.all().prefetch_related('children__pets')
[{'name': parent.name, 'children': [{'name': child.name, 'pets': [{'name':pet.name, 'type':pet.type} for pet in child.pets.all()]} for child in parent.children.all()]} for parent in parents]