如何在django中使用list serializer根据继承的序列化器进行序列化?

时间:2017-08-01 04:21:20

标签: django design-patterns django-rest-framework multiple-inheritance django-serializer

让我们假设有三种模型Animal,Cat,Dog,其中Cat和Dog从父类Animal继承。

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.

1 个答案:

答案 0 :(得分:0)

这不是设计模式解决方案,但为什么不让序列化器迭代(有人说 iterator 模式?;-))字段并序列化它们?为什么需要儿童序列化器? 如果您不希望序列化程序序列化所有字段,则让每个 animal 子项指定可序列化字段的数组,然后对其进行序列化。
此解决方案允许您为 animal 的所有子类设置一个序列化程序。