Created
November 10, 2015 11:08
-
-
Save eugena/6e17a0f79fe7de2c1d0d to your computer and use it in GitHub Desktop.
Writable hybrid of PrimaryKeyRelated and SerializerMethod Fields
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 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