Created
October 7, 2019 17:18
-
-
Save surenkov/5c696032a7fbb2b2b35e560456f5611e to your computer and use it in GitHub Desktop.
Django REST Framework context default value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from operator import methodcaller | |
from django.utils.functional import cached_property | |
from typing import Union | |
class ContextDefaultValue: | |
""">>> field = serializers.HiddenField( | |
>>> default=ContextDefaultValue("some_context_attr") | |
>>> )""" | |
def __init__(self, attr: Union[str, callable], default=None): | |
self.context_attr = attr | |
self.default = self.value = default | |
def set_context(self, parent): | |
self.value = self._context_getter(parent.context) | |
def __call__(self): | |
return self.value | |
def __repr__(self): | |
return f"{self.__class__.__name__}([{self.context_attr}, {self.default}])" | |
@cached_property | |
def _context_getter(self): | |
if callable(self.context_attr): | |
return self.context_attr | |
return methodcaller("get", self.context_attr, self.default) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment