3

我正在使用 Django Rest Framework 和 django-polymorphic-tree 构建一个树状分层数据库系统。我有两个模型——BaseTreeNode 和 DescriptionNode(后一个是从 BaseTreeNode 派生的)。具体来说,这是我的models.py

class BaseTreeNode(PolymorphicMPTTModel):
    parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name=_('parent'))
    title = models.CharField(_("Title"), max_length=200)

    def __str__(self):
        return "{}>{}".format(self.parent, self.title)

    class Meta(PolymorphicMPTTModel.Meta):
        verbose_name = _("Tree node")
        verbose_name_plural = _("Tree nodes")


# Derived model for the tree node:

class DescriptionNode(BaseTreeNode):
    description = models.CharField(_("Description"), max_length=200)

    class Meta:
        verbose_name = _("Description node")
        verbose_name_plural = _("Description nodes")

因此,每个title字段(属于BaseTreeNode)都有一个关联description字段(属于 DescriptionNode)。

Django 管理视图

现在,我想要的只是一个返回整个树的嵌套表示的 JSON。目前,我只定义了一个带有递归字段的简单序列化程序。我的序列化程序.py

from rest_framework_recursive.fields import RecursiveField

class DescriptionNodeSerializer(serializers.ModelSerializer):
    class Meta:
        model = DescriptionNode
        fields = ('description',)

class BaseTreeNodeSerializer(serializers.ModelSerializer):
    subcategories = serializers.ListSerializer(source="children",child=RecursiveField())  
    class Meta:
        model = BaseTreeNode
        fields = ('id', 'title', 'subcategories')

这给了我(仅适用于 BaseTreeNodeSerializer):

[
  {
    "id": 1,
    "title": "Apple",
    "subcategories": [
      {
        "id": 2,
        "title": "Contact Person",
        "subcategories": []
      },
      {
        "id": 3,
        "title": "Sales Stage",
        "subcategories": [
          {
            "id": 4,
            "title": "Suspecting",
            "subcategories": [
              {
                "id": 5,
                "title": "Contact verification",
                "subcategories": []
              }
            ]
          },
          {
            "id": 6,
            "title": "Prospecting",
            "subcategories": [
              {
                "id": 7,
                "title": "Client Detail",
                "subcategories": []
              }
            ]
          }
        ]
      },
      {
        "id": 9,
        "title": "Medium",
        "subcategories": [
          {
            "id": 10,
            "title": "Status",
            "subcategories": []
          }
        ]
      },
      {
        "id": 13,
        "title": "Remainder",
        "subcategories": []
      }
    ]
  }
]

我的问题是,如何在层次结构description中包含与每个title字段(来自 BaseTreeNode 模型)相关联的字段(来自派生模型)?就像是:

... {
                "id": 5,
                "title": "Contact verification",
                "description": "Verified"
                "subcategories": []
              } ...
4

1 回答 1

3

相应的模型如下:

class DescriptionNode(BaseTreeNode):
    basetreenode = models.OneToOneField(BaseTreeNode, related_name="base_tree")
    description = models.CharField(_("Description"), max_length=200)

    class Meta:
        verbose_name = _("Description node")
        verbose_name_plural = _("Description nodes")

序列化程序如下:

from rest_framework_recursive.fields import RecursiveField

class BaseTreeNodeSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()
    subcategories = serializers.ListSerializer(source="children",child=RecursiveField())

    class Meta:
        model = BaseTreeNode
        fields = ('id', 'title', 'description', 'subcategories')

    def get_description(self, obj):
        return obj.base_tree.description #base_tree is related name of basetreenode field
于 2017-12-27T06:07:53.403 回答