Django:从查询相关模型创建嵌套字典的最有效方法?

时间:2016-06-04 05:53:10

标签: django dictionary django-queryset django-orm

在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

1 个答案:

答案 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]