0
Animal、Cat、Dogの3つのモデルがあると仮定します。ここで、CatとDogは親クラスAnimalから継承します。djangoでリストシリアライザを使用して継承されたシリアライザに従ってシリアライズするにはどうすればよいですか?
class Animal:
name
class Cat:
sleep_hours
class Dog:
breed
sleep_hoursおよびbreedはそれぞれ猫および犬の相互排他的特性であると考える。今、私たちは、シリアライザ持っている: -
AnimalSerializer:
name
CatSerializer(AnimalSerializer):
sleep_hours
DogSerializer(AnimalSerializer):
breed
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.