django - 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/
如果有人也可以为此提供线索,我将不胜感激。
解决方案
推荐阅读
- c++builder - 使用 Indy10 组件从 alphavantage.co 下载
- node.js - Mongoose Schema中数组内的重复值
- angular - 将我的 Angular 6 指令与 DOM 解耦
- ios - 如何通过 Swift 中的 ContainerView 更改 TableView 中项目的属性?
- vba - Excel VBA - 在某些文本后删除部分 URL
- informatica - 带有“ä”等特殊字符的 Informatica 源文件名
- amazon-web-services - 是否可以使用 powershell 脚本创建批量 aws ALB?
- javascript - “===”是反应中的意外标记
- ios - 如何让 iOS 变慢
- javascript - 试图过滤掉对象中的值