lundi 31 juillet 2017

How to use list serializer in django to serialize according to inherited serializer?

Lets assume there are three models Animal, Cat, Dog where Cat and Dog are inheriting from parent class Animal.

class Animal:
   name
class Cat:
   sleep_hours
class Dog:
   breed

Considering that sleep_hours and breed are mutually exclusive property of cat and dog respectively. Now we have serializers :- enter codAnimalSerializer: name CatSerializer(AnimalSerializer): sleep_hours DogSerializer(AnimalSerializer): breede here

Now we want to develop an API where we return all the information about animal so it should return something like this 
[
{'tommy', 'pug'},
{'kitty', '10'},
]
So consider animal class is linked to user i.e. user.animals returns a list of animals (parent class) we want to use modelSerialiser on user.
class UserAnimalSerializer(serializers.ModelSerializer):
    animals = AnimalSerializer(read_only=True)

 class Meta:
        model = User
        fields = ('animals')

Now we want to use different serializer(child serializer) based on the instance type. Is there any good way to handle these type of scenarios. Please comment if there is some confusion about the question.

Aucun commentaire:

Enregistrer un commentaire