Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
django-polymorphic-tree serializer

I would like to serialize all the nodes in my PolymorphicMPTTModel with their corresponding fields. Following the documentation django-polymorphic and django-mptt i get this:

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

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

               ]
            }
         ]
      }
   ]
}

The structure is fine, but the fields of the children are missing.

Models:

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

Serializers:

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')

View:

class MenuView(viewsets.ModelViewSet):
    queryset = Menu.objects.all()
    queryset = queryset.toplevel()
    serializer_class = MenuItemModuleSerializer
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I know I'm kinda late to the party but I had the same issue and finally found a solution that is working for me.


As django-rest-polymorphic states, you need a mapping between models and serializers:

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

Your RecursiveField() creates a serializer instance from its parent class. That makes all your child objects using the MenuItemModuleSerializer and thus missing child fields.

Every child needs to get mapped to its serializer using ProjectPolymorphicSerializer

RecursiveField(to='ProjectPolymorphicSerializer')

Change your MenuItemModuleSerializer to this:

class MenuItemModuleSerializer(serializers.ModelSerializer):
    subcategories = serializers.ListSerializer(source="children", child=RecursiveField(to='ProjectPolymorphicSerializer'))
    class Meta:
        model = Menu
        fields = ('title','subcategories')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!