DRF将数据传递到RelatedField

时间:2018-08-03 15:59:07

标签: python django django-rest-framework

我有一个序列化程序和一个与通用外键关系相关的字段 应该用于序列化content_object实例的ContentType。我需要检查要在相关字段中序列化的type对象的Notification,以正确知道要在其中序列化为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',
        ]

2 个答案:

答案 0 :(得分:1)

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

示例

Notification

答案 1 :(得分:1)

您可以使用SerializerMethodField作为序列化通用FK关系,

class Content_Model_1_serializer(serializers.ModelSerializer):
    # you code
class Content_Model_2_serializer(serializers.ModelSerializer):
    # your code

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

    def get_content_object(self, notification):
        if isinstance(notification.content_object, Content_Model_1):
            return Content_Model_1_serializer(notification.content_object).data
        if isinstance(notification.content_object, Content_Model_2):
            return Content_Model_2_serializer(notification.content_object).data
        ## and so on
        return None  # default case

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

Content_Model_1Content_Model_2是通过通用FK关系关联的模型,而Content_Model_1_serializerContent_Model_2_serializer是序列化程序。