在Django中

时间:2018-11-30 15:59:55

标签: python django python-3.x django-serializer

我有一个这样的继承模型,

基类,

class PrivateMessage(Base):
    sender = models.ForeignKey(User, related_name='privatemessage_set', on_delete=models.CASCADE, null=True)
    room = models.ForeignKey(PrivateRoom, on_delete=models.CASCADE, related_name='message_set', null=True)
    message_type = models.CharField(max_length=255, null=True)

孩子。

class PrivateTextMessage(PrivateMessage):
        body = models.TextField(null=True, blank=True)

class PrivateImageMessage(PrivateMessage):
        image = models.ImageField(upload_to=attachment_images_path, null=True, blank=True)

我正在对它们进行多态序列化,

class PublicMessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PublicMessage
        fields = '__all__'

    def to_representation(self, obj):
        if isinstance(obj, PublicTextMessage):
            return PublicTextMessageSerializer(obj, context=self.context).to_representation(obj)
        elif isinstance(obj, PublicImageMessage):
            return PublicImageMessageSerializer(obj, 
        return super(PublicMessageSerializer, self).to_representation(obj)


class PublicTextMessageSerializer(serializers.ModelSerializer):
    sender = UserSerializer(read_only=True)
    receiver = RoomSerializer(read_only=True)

    class Meta:
        model = PublicTextMessage
        fields = ('id', 'sender', 'receiver', 'body', 'message_type', 'created', 'modified',)


class PublicImageMessageSerializer(serializers.ModelSerializer):
    sender = UserSerializer(read_only=True)
    receiver = RoomSerializer(read_only=True)
    image = serializers.ImageField(use_url=True)

    class Meta:
        model = PublicImageMessage
        fields = ('id', 'sender', 'receiver', 'image', 'message_type', 'created', 'modified',)

问题在于串行器仅呈现基类中存在的字段。例如,PublicImageMes​​sage中的image字段永远不会被渲染。

有人可以帮助我进行条件渲染吗?该条件渲染了该类的所有字段。

  

PS:这些类具有PublicMessageType对象。我已经尝试过使用   并进行序列化,但是除了笨拙之外,在这种情况下   字段以空值呈现。

0 个答案:

没有答案