本文介绍了正确使用“可调用的默认功能".在Django REST Framework(DRF)中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在默认可调用函数中访问 序列化器实例 任何相关参数 是DRF字段?

How can I access the serializer instance or any relevant arguments in the default callable function of DRF field?

我有一个如下的序列化器配置,

I have a serializer configuration as below,

def bar_value_callable_function(serializer_instance):
    if serializer_instance.context['request'].method == 'GET':
        return 'return value One'
    return 'return value Two'

FooSerializer类(serializers.Serializer):bar = serializers.CharField( source ='foo.bar',默认= bar_value_callable_function )

class FooSerializer(serializers.Serializer): bar = serializers.CharField(source='foo.bar', default=bar_value_callable_function)

当我尝试将数据序列化为

and when I try to serialize the data as,

serializer = FooSerializer(foo_instance, context={'request': request})
print(serializer.data)

我犯错了,

TypeError: bar_value_callable_function() missing 1 required positional argument: 'serializer_instance'

推荐答案

更新
对于DRF> = 3.12,请使用此默认类别之王

Update
For DRF>=3.12, use this king of default class

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'


类实例 而不是 function 传递给 default 自变量


pass a class instance instead of function to the default argument

# 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'

# serializer
class FooSerializer(serializers.Serializer):
    bar = serializers.CharField(source='foo.bar', default=DefaultBarValue())

这篇关于正确使用“可调用的默认功能".在Django REST Framework(DRF)中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 23:23