首页 > 解决方案 > DRF 将数据传递到相关字段

问题描述

我有一个序列化器和一个用于通用外键关系的相关字段,应该用于序列化content_object哪个是一个ContentType实例。我需要检查我在相关字段中序列化typeNotification对象,以正确知道哪些附加字段要序列化到那里的data参数中。实现这一目标的最佳方法是什么?

class NotificationRelatedField(serializers.RelatedField):

    def to_representation(self, value):
        data = {}
        # Need to check notification 'type' here
        return data


class NotificationRetrieveSerializer(serializers.ModelSerializer):
    content_object = NotificationRelatedField(read_only=True)

    class Meta:
        model = Notification
        fields = [
            'id',
            'created_at',
            'is_read',
            'type',
            'content_object',
        ]

标签: pythondjangodjango-rest-framework

解决方案


您需要重写序列化程序的to_representation方法以使用实例调用字段的to_representation方法Notification,而不是使用字段的值。

示例

class NotificationRetrieveSerializer(serializers.ModelSerializer):
    content_object = NotificationRelatedField(read_only=True)

    class Meta:
        model = Notification
        fields = [
            'id',
            'created_at',
            'is_read',
            'type',
            'content_object',
        ]

    # override to_representation method
    def to_representation(self, instance):
        # python3 for `super` call
        result = super().to_representation(instance)

        # python2 for `super` call
        # result = super(
        #     NotificationRetrieveSerializer, self
        # ).to_representatio(instance)

        # here you call your field's `to_representation` with current instance
        # as the argument rather than as the `value` of the field.
        result['content_object'] = content_object_field.to_representation(instance)

        return result

class NotificationRelatedField(serializers.RelatedField):

    # here `value` is now the `Notification` instance
    def to_representation(self, value):
        data = {}

        # get the type and this field's value
        type = value.type
        content_object = value.content_object

        return data

推荐阅读