2

我想用相应的字段序列化我的 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
4

1 回答 1

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')
于 2020-04-07T23:05:47.827 回答