Skip to content

Instantly share code, notes, and snippets.

@malinich
Created August 4, 2016 05:53
Show Gist options
  • Save malinich/84cb280ab882f1848cdc0c933414e639 to your computer and use it in GitHub Desktop.
Save malinich/84cb280ab882f1848cdc0c933414e639 to your computer and use it in GitHub Desktop.
class AttrKeyRelatedField(PrimaryKeyRelatedField):
def __init__(self, **kwargs):
self.attr_field = kwargs.pop('attr_field')
super(AttrKeyRelatedField, self).__init__(**kwargs)
def use_pk_only_optimization(self):
return False
def to_internal_value(self, data):
if self.pk_field is not None:
data = self.pk_field.to_internal_value(data)
try:
filter_ = {self.attr_field: data}
return self.get_queryset().get(**filter_)
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 value
class MsServerSerializer(serializers.Serializer):
client_type = AttrKeyRelatedField(queryset=ExtSystemClient.objects.all(),
pk_field=CharField(),
attr_field='client_type')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment