django-polymorphic-tree serializer

时间:2017-04-27 15:18:32

标签: django django-rest-framework django-mptt django-polymorphic

我想序列化我的PolymorphicMPTTModel中的所有节点及其相应的字段。在文档django-polymorphic和django-mptt之后我得到了这个:

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

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

               ]
            }
         ]
      }
   ]
}

结构很好,但孩子的田地都不见了。

模型:

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

1 个答案:

答案 0 :(得分:0)

我知道我参加聚会有点晚,但是我遇到了同样的问题,终于找到了对我有用的解决方案。


django-rest-polymorphic所述,您需要模型与序列化程序之间的映射:

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

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

每个孩子都需要使用 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')