序列化多个链接模型的列表

序列化多个链接模型的列表

本文介绍了Django:序列化多个链接模型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个具有相同父基类的不同模型。有没有办法使用Django Rest Framework序列化程序或serpy序列化包含两个子模型实例的链表?

Given two different models, with the same parent base class. Is there any way, using either Django Rest Framework Serializers or serpy, to serialize a chained list containing instances of both the child models?

给出一些示例模型:

class BaseModel(models.Model):
   created_at = models.DateField()

   class Meta:
       abstract = True


class ChildModel1(BaseModel):
    field_one = models.TextField()


class ChildModel2(BaseModel):
    field_two = models.TextField()

和一个示例视图:

def get(self, request):

    q1 = ChildModel1.objects.all()
    q2 = ChildModel2.objects.all()

    chained_list = sorted(
        chain(q1, q2),
        key=attrgetter('created_at'))

    serializer = BaseModelSerializer(chained_list, many=True)

模型取自问题。

在我目前的尝试下,我得到一个相当明显的错误,内容如下:

With my current attempts I get a quite obvious error saying something like:

AttributeError: 'ChildModel1' object has no attribute 'field_two'

我知道将两个模型与

我测试过的一些序列化器示例:

Some examples of serializers I have tested:

第一个示例:

class BaseModelSerializer(serializers.ModelSerializer):

   class Meta:
       model = BaseModel

第二个示例:

class BaseModelSerializer(serpy.Serializer):
   created_at = serpy.StrField()

   field_one = serpy.StrField(required=False)
   field_two = serpy.StrField(required=False)


解决方案

您可以定义序列化程序,该序列化程序将根据模型将两个或多个序列化程序组合在一起:

You can define serializer that will combine two or more serializers together based on model:

class Model1Serializer(serializers.Serializer):
    ...

class Model2Serializer(serializers.Serializer):
    ...

class SummarySerializer(serializers.Serializer):
    """ Serializer that renders each instance with its own specific serializer """

    @classmethod
    def get_serializer(cls, model):
        if model == Model1:
            return Model1Serializer
        elif model == Model2:
            return Model2Serializer

    def to_representation(self, instance):
        serializer = self.get_serializer(instance.__class__)
        return serializer(instance, context=self.context).data

这将适用于所有型号,不仅适用于一类儿童。

This will work for any models, not only for childs of one class.

这篇关于Django:序列化多个链接模型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:41