【发布时间】:2018-01-07 19:05:36
【问题描述】:
假设有三个模型 Animal、Cat、Dog,其中 Cat 和 Dog 继承自父类 Animal。
class Animal:
name
class Cat:
sleep_hours
class Dog:
breed
考虑到 sleep_hours 和breed 分别是cat 和dog 的互斥属性。现在我们有了序列化器:-
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.
【问题讨论】:
标签: django design-patterns django-rest-framework multiple-inheritance django-serializer