Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Created December 11, 2014 00:24
Show Gist options
  • Save AndrewIngram/5c79a3e99ccd20245613 to your computer and use it in GitHub Desktop.
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
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