gpt4 book ai didi

django 多态树序列化器

转载 作者:行者123 更新时间:2023-12-05 06:40:03 25 4
gpt4 key购买 nike

我想用相应的字段序列化我的 PolymorphicMPTTModel 中的所有节点。按照文档 django-polymorphic 和 django-mptt 我得到这个:

{  
"count":1,
"next":null,
"previous":null,
"results":[
{
"title":"Submenu",
"subcategories":[
{
"title":"Plato1",
"subcategories":[

]
},enter code here
{
"title":"Plato2",
"subcategories":[

]
}
]
}
]
}

结构没问题,就是少了 child 的字段。

模型:

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

class SubMenu(Menu):
titulo = models.CharField("Titulo", max_length=200,default="not defined")

class Plato(Menu):
titulo = models.CharField("Titulo",max_length=200,default="not defined")
descripcion = models.TextField()
ingredientes = JSONField()
precio = models.PositiveSmallIntegerField(default=0)
# Extra settings:
can_have_children = False

序列化器:

class PlatoSerializer(serializers.ModelSerializer):
class Meta:
model = Plato
fields = ('titulo', 'descripcion', 'ingredientes', 'precio')
class SubMenuSerializer(serializers.ModelSerializer):
class Meta:
model = SubMenu
fields = ('titulo',)

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

查看:

class MenuView(viewsets.ModelViewSet):
queryset = Menu.objects.all()
queryset = queryset.toplevel()
serializer_class = MenuItemModuleSerializer

最佳答案

我知道我有点晚了,但我遇到了同样的问题,并最终找到了适合我的解决方案。


作为django-rest-polymorphic状态,你需要模型和序列化器之间的映射:

class ProjectPolymorphicSerializer(PolymorphicSerializer):
model_serializer_mapping = {
Menu: MenuItemModuleSerializer,
SubMenu: SubMenuSerializer,
Plato: PlatoSerializer
}

您的 RecursiveField() 从其父类创建一个序列化程序实例。这使得您的所有子对象都使用 MenuItemModuleSerializer,因此缺少子字段。

每个 child 都需要使用 ProjectPolymorphicSerializer 映射到其序列化器

RecursiveField(to='ProjectPolymorphicSerializer')

将您的 MenuItemModuleSerializer 更改为:

class MenuItemModuleSerializer(serializers.ModelSerializer):
subcategories = serializers.ListSerializer(source="children", child=RecursiveField(to='ProjectPolymorphicSerializer'))
class Meta:
model = Menu
fields = ('title','subcategories')

关于django 多态树序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43661778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com