Skip to content

Instantly share code, notes, and snippets.

@jefftriplett
Created June 17, 2022 19:30
Show Gist options
  • Save jefftriplett/be46e5f338facd9004c942280f3916e1 to your computer and use it in GitHub Desktop.
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.
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