Created
December 11, 2014 00:24
-
-
Save AndrewIngram/5c79a3e99ccd20245613 to your computer and use it in GitHub Desktop.
Django Rest Framework field for reading a serializer but writing a primary key
This file contains 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 RichPrimaryKeyRelatedField(serializers.RelatedField): | |
def __init__(self, serializer, *args, **kwargs): | |
self.many = kwargs.get('many', False) | |
self.serializer = serializer | |
super(RichPrimaryKeyRelatedField, self).__init__(*args, **kwargs) | |
def to_internal_value(self, data): | |
try: | |
return self.get_queryset().get(pk=data) | |
except ObjectDoesNotExist: | |
self.fail('does_not_exist', pk_value=data) | |
except (TypeError, ValueError): | |
self.fail('incorrect_type', data_type=type(data).__name__) | |
def to_representation(self, value): | |
return self.serializer(value, many=self.many).data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment