Skip to content

Instantly share code, notes, and snippets.

@court-jus
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save court-jus/add58c1752264b56ce8b to your computer and use it in GitHub Desktop.
Save court-jus/add58c1752264b56ce8b to your computer and use it in GitHub Desktop.
class SerializedRelatedField(relations.RelatedField):
"""
A read-write field that uses a serializer when reading the relation but
expects the pk to be provided when creating or updating.
"""
default_error_messages = {
'does_not_exist': _('Object with pk={value} does not exist.'),
'invalid': _('Invalid value.'),
'needs_id': _('The data provided is missing the "id" field.'),
}
def __init__(self, serializer, **kwargs):
self.serializer = serializer
super(SerializedRelatedField, self).__init__(**kwargs)
def to_internal_value(self, data):
if 'id' not in data:
self.fail('needs_id')
pk = data['id']
try:
return self.get_queryset().get(pk=pk)
except ObjectDoesNotExist:
self.fail('does_not_exist', value=smart_text(pk))
except (TypeError, ValueError):
self.fail('invalid')
def to_representation(self, obj):
return self.serializer(obj).data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment