Created
June 17, 2022 19:30
-
-
Save jefftriplett/be46e5f338facd9004c942280f3916e1 to your computer and use it in GitHub Desktop.
Example DRF Prefix Mixin for accepted a dict() that might have a model prefix.
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
class PrefixedMixin: | |
def __init__(self, *args, **kwargs): | |
self._prefix = kwargs.pop("prefix", None) | |
super().__init__(*args, **kwargs) | |
def to_internal_value(self, data): | |
"""Dict of native values <- Dict of primitive datatypes.""" | |
if self._prefix: | |
data = { | |
key.replace(f"{self._prefix}_", ""): value | |
for key, value in data.items() | |
if key.startswith(self._prefix) | |
} | |
data = super().to_internal_value(data) | |
return data | |
def to_representation(self, instance): | |
"""Object instance -> Dict of primitive datatypes.""" | |
if self._prefix: | |
return { | |
f"{self._prefix}_{key}": value | |
for key, value in super().to_representation(instance).items() | |
} | |
return super().to_representation(instance) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment