假设有三个模型动物,猫,狗,其中猫和狗继承自父类动物。
class Animal:
name
class Cat:
sleep_hours
class Dog:
breed
考虑到sleep_hours和品种分别是猫和狗的相互排斥财产。现在我们有序列化程序:-
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.
这不是一个设计模式解决方案,但为什么不让序列化程序迭代(有人说迭代器模式吗?;-((字段并序列化它们呢?为什么需要子序列化程序?如果不希望序列化程序序列化所有字段,
请让每个动物子项指定一个可序列化字段数组,然后序列化这些字段。
此解决方案允许您为动物的所有子类使用一个序列化程序。