Serializing multiple inheritance models in Django REST Framework

28 Views Asked by At

I have this model structure:

class Main (models.Model):
    name=models.Charfield(max_length=50)
    ...
class Category (Main):
    type=models.Charfield(max_length=50)
    ...
class SubCategory1(Category):
     charasteristic=models.Charfield(max_length=60)
     ...
class SubCategory2(Category):
     charasteristic=models.Charfield(max_length=60)

That is, there is one parent from which one children inherits, from which, in turn, multiple childrens inherit. For the API, I would like to show a complete structure in the json, from grandparent to every grandson. I mean, if I use the following serializer:

class Subcategory1_serializer(serializers.ModelSerializer):
    class Meta:
        model=Subcategory1
        fields=("__all__")

it returns something like this:

[
    {
        "name":
        "type":
        "charasteristic":
     },
]

But this forces me to create a serializer for every single Subcategory. I want to get it in an automatic way.

I've tried accessing via subclasses, I took a look at some proposals about Polymorphism (but I get lost) and I have tried to redefine inheritance in terms of OneToOne relationships, but I still cannot solve it (and it complicates data introduction from the admin panel). Any help would be great, Thanks in advance

0

There are 0 best solutions below