0

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

2
  • I think another problem might be how the receiver end would handle heterogeneous data. Inheritance is a strong concept, but does not fit very well with data, especially data in databases. Inheritance is likely most powerful as a "template method", not that much to combine things that are essentially different. Commented Dec 23, 2023 at 17:52
  • 1
    Thanks for your point @willeM_VanOnsem , I'll take a look at the template method you mentioned. I have already solved the issue as suggested here: stackoverflow.com/a/42282447/23148243 . Great community Commented Dec 24, 2023 at 18:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.