Skip to content

Instantly share code, notes, and snippets.

@eugena
Created November 10, 2015 11:08
Show Gist options
  • Save eugena/6e17a0f79fe7de2c1d0d to your computer and use it in GitHub Desktop.
Save eugena/6e17a0f79fe7de2c1d0d to your computer and use it in GitHub Desktop.
Writable hybrid of PrimaryKeyRelated and SerializerMethod Fields
from rest_framework import serializers
class HybridPrimaryKeyRelatedAndSerializerMethodField(serializers.PrimaryKeyRelatedField):
"""
PrimaryKeyRelatedField & SerializerMethodField
"""
def __init__(self, method_name=None, **kwargs):
self.method_name = method_name
super(HybridPrimaryKeyRelatedAndSerializerMethodField, self).__init__(**kwargs)
def to_representation(self, value):
"""
Transform the *outgoing* native value into primitive data.
"""
method = getattr(self.parent, self.method_name)
return method(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment