Proper Usage Of "callable Default Function" In Django Rest Framework (drf)
Question: How can I access the serializer instance or any relevant arguments in the default callable function of DRF field? Scenario: I have a serializer configuration as below, d
Solution 1:
Update For DRF>=3.12, use this king of default class
classDefaultBarValue:
requires_context = True
def __call__(self, serializer_instance):
if serializer_instance.context['request'].method == 'GET':
return'return value One'return'return value Two'
pass a class instance instead of function to the default
argument
# default callable classclassDefaultBarValue:
"""
"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.12defset_context(self, serializer_instance): # not required for DRF>=3.12
self.serializer_instance = serializer_instance
def__call__(self, serializer_instance=None):
if serializer_instance isNone: # will be None for older versions of DRFif self.serializer_instance.context['request'].method == 'GET':
return'return value One'return'return value Two'else: # for DRF>=3.12if serializer_instance.context['request'].method == 'GET':
return'return value One'return'return value Two'
# serializerclass FooSerializer(serializers.Serializer):
bar = serializers.CharField(source='foo.bar', default=DefaultBarValue())
Post a Comment for "Proper Usage Of "callable Default Function" In Django Rest Framework (drf)"