0

I am solving an equivalent problem to the following. I need to serialize django models which have following criteria:

  • Base (abstract) class from django model containing a "type" field where I can store type of goods (i.e. fruit, clothes...)
  • Derived classes for different type of goods (fruit has weight, clothes have color)

I would like to serialize (into JSON) the list of any goods for REST API framework. I do not know how to make it the best to use framework capabilities of serialized object validation etc.

majvan
  • 51
  • 6

1 Answers1

0

You can define serializer that will combine two or more serializers together based on model:

class Model1Serializer(serializers.Serializer):
    ...

class Model2Serializer(serializers.Serializer):
    ...

class SummarySerializer(serializers.Serializer):
    """ Serializer that renders each instance with its own specific serializer """

    @classmethod
    def get_serializer(cls, model):
        if model == Model1:
            return Model1Serializer
        elif model == Model2:
            return Model2Serializer

    def to_representation(self, instance):
        serializer = self.get_serializer(instance.__class__)
        return serializer(instance, context=self.context).data

This will work for any models, not only for childs of one class. origin answer is here,answered by zymud at Jan 19 14:52.

Ykh
  • 7,567
  • 1
  • 22
  • 31