JPG*_*JPG 3 python django django-serializer django-rest-framework
如何在DRF 字段的默认可调用函数中访问序列化程序实例或任何相关参数?
我有一个如下的序列化程序配置,
def bar_value_callable_function(serializer_instance):
if serializer_instance.context['request'].method == 'GET':
return 'return value One'
return 'return value Two'
class FooSerializer(serializers.Serializer):
bar = serializers.CharField(source='foo.bar', default=bar_value_callable_function)
Run Code Online (Sandbox Code Playgroud)
当我尝试将数据序列化为
serializer = FooSerializer(foo_instance, context={'request': request})
print(serializer.data)
Run Code Online (Sandbox Code Playgroud)
我收到错误,
TypeError: bar_value_callable_function() missing 1 required positional argument: 'serializer_instance'
Run Code Online (Sandbox Code Playgroud)
更新
对于 DRF>=3.12,使用这个默认类之王
class DefaultBarValue:
requires_context = True
def __call__(self, serializer_instance):
if serializer_instance.context['request'].method == 'GET':
return 'return value One'
return 'return value Two'Run Code Online (Sandbox Code Playgroud)
将类实例而不是函数传递给default参数
# default callable class
class DefaultBarValue:
"""
"Method `set_context` on defaults is deprecated and will
no longer be called starting with 3.12. Instead set
`requires_context = True` on the class, and accept the
context as an additional argument.
"""
requires_context = True # for DRF>=3.12
serializer_instance = None # not required for DRF>=3.12
def set_context(self, serializer_instance): # not required for DRF>=3.12
self.serializer_instance = serializer_instance
def __call__(self, serializer_instance=None):
if serializer_instance is None: # will be None for older versions of DRF
if self.serializer_instance.context['request'].method == 'GET':
return 'return value One'
return 'return value Two'
else: # for DRF>=3.12
if serializer_instance.context['request'].method == 'GET':
return 'return value One'
return 'return value Two'Run Code Online (Sandbox Code Playgroud)
# serializer
class FooSerializer(serializers.Serializer):
bar = serializers.CharField(source='foo.bar', default=DefaultBarValue())Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
644 次 |
| 最近记录: |