Django Rest Framework와 django-polymorphic-tree를 사용하여 나무와 같은 계층 적 데이터베이스 시스템을 구축하고 있습니다. BaseTreeNode와 DescriptionNode라는 두 모델이 있습니다 (나중에 BaseTreeNode에서 파생됩니다). 특히, 여기 내 models.py
:Django Rest 프레임 워크 : 파생 모델 시리얼 라이저 필드
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에 속하는)가 있습니다.
이제, 내가 가진하고자하는 모든 내 전체 트리의 중첩 된 표현을 반환하는 JSON이다. 지금은 재귀 필드가있는 간단한 serializer 만 정의했습니다. (만 BaseTreeNodeSerializer에 대한) 저를주는 내 serializers.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')
:
[
{
"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": []
} ...
네를! 매력처럼 작동합니다 (거의). 마이그레이션을 삭제하고 다시 실행하여 정렬 된 "django.db.utils.IntegrityError : UNIQUE 제약 조건"문제가 지속되었습니다. 건배! –