【问题标题】:How to use list serializer in django to serialize according to inherited serializer?如何在django中使用列表序列化器根据继承的序列化器进行序列化?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2018-07-25
      • 2019-06-17
      相关资源
      最近更新 更多