How to merge two models inherited from Django into one serializer

Viewed 50

In Django, is there a way to combine two models that inherit the same class into one serializer?

from django.db.models import Model
class A(Model):
    a = IntegerField(...)
    # other fields...
    
    class Meta:
        abstract = True

class B(A):
# There may or may not be such a thing as class C.

class C(A):
# There may or may not be such a thing as class B.

I have code like above.

Could it be possible to create a serializer based on the class A model?

I tried to create a view table in SQL, but gave up due to performance issues.

Any good ideas please. It's so painful...

1 Answers

In general it is not a good idea to reuse serializes because doing so may expose you to unexpected behavior, when something changes in the base serializer or when you add/remove attributes to one of your models.

If model B and C have some attributes in common, then perhaps, you should consider changing your DB design.

However, in this case I would define 2 serializes that have the attribute of the abstract model:


class BSerializer(serializers.Serializer):
    a = serialzier.IntegerField()
    ... 

class CSerializer(serialziers.Serializer):
    a = serializer.IntegerField()
    ... 

Related