首页 > 解决方案 > DRF 序列化程序中的 context 和 _context 有什么区别?

问题描述

在嵌套序列化程序中,我尝试在创建序列化程序时传递一些上下文。但似乎内部序列化程序的上下文被外部序列化程序的上下文覆盖。用下面的例子解释:

class WebsiteImagesSerializer(serializers.ModelSerializer):
    class Meta:
        list_serializer_class = FilterSerializer
        model = WebsiteImages
        fields = ('id', 'website', 'image_url', 'category')


    def __init__(self, *args, **kwargs):
        # Instantiate the superclass normally
        super(WebsiteImagesReadSerializer, self).__init__(*args, **kwargs)
        print('context at init of WebsiteImagesSerializer', self.context)
        print('_context at init of WebsiteImagesSerializer', self._context)

    def to_representation(self, data):
        '''
        updating the image_url to complete url which can be used
        '''
        print('context at to_representation of WebsiteImagesSerializer', self.context)
        print('_context at to_representation of WebsiteImagesSerializer', self._context)
        repr = super(WebsiteImagesReadSerializer, self).to_representation(data)
        return repr



class FilterSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        print('context at FilterSerializer', self.context)
        print('_context at FilterSerializer', self._context)
        data = data.filter(status=True)
        return super(FilterSerializer, self).to_representation(data)



class WebsiteSerializer(serializers.ModelSerializer):
    websiteimages_set = WebsiteImagesSerializer(many=True, read_only=True, context={'filter': {'category': 'logo'}})

    class Meta:
        model = Website
        fields = ('id', 'url', 'websiteimages_set')

WebsiteSerializer现在,当我使用上下文数据创建一个 Object{'required_fields': []}并获取其数据时,输出如下:

context at init of WebsiteImagesSerializer {'filter': {'category': 'logo'}}
_context at init of WebsiteImagesSerializer {'filter': {'category': 'logo'}}

context at FilterSerializer {'required_fields': []}
_context at FilterSerializer {'filter': {'category': 'logo'}}

context at to_representation of WebsiteImagesSerializer {'required_fields': []}
_context at to_representation of WebsiteImagesSerializer {'filter': {'category': 'logo'}}

这种行为是预期的吗?为什么 _context 之后会更新__init__

另外,我在这里尝试的是尝试根据模型中的选择字段过滤掉序列化器中的数据。我不希望发送完整的 websiteimage_set。但是希望它们基于一个字段进行分组,并且不想为每个字段创建单独的序列化器。这个问题在这里解释:https ://www.reddit.com/r/django/comments/nzp1rn/how_to_separate_out_data_of_a_nested_serializer/

如果有人也可以为此提供线索,我将不胜感激。

标签: djangodjango-rest-frameworkdjango-serializer

解决方案


推荐阅读