给定两个不同的模型,它们具有相同的父基类。是否可以使用Django Rest Framework序列化程序或serpy序列化包含两个子模型的实例的链表?
给定一些示例模型:
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)
链接模型的方法来自该问题的答案。
通过我目前的尝试,我得到了一个非常明显的错误,内容如下:
AttributeError: 'ChildModel1' object has no attribute 'field_two'
我知道将两种模型与不同领域混合使用不是最佳做法,但就我而言,我认为这是必要的。
我测试过的一些序列化器示例:
第一个例子:
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)
zymud.. 6
您可以定义序列化器,该序列化器将根据模型将两个或多个序列化器组合在一起:
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
这将适用于任何模型,不仅适用于一类儿童。
您可以定义序列化器,该序列化器将根据模型将两个或多个序列化器组合在一起:
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
这将适用于任何模型,不仅适用于一类儿童。