Skip to content

Instantly share code, notes, and snippets.

@arthuralvim
Created September 7, 2014 22:10
Show Gist options
  • Select an option

  • Save arthuralvim/13a0464761400975a9da to your computer and use it in GitHub Desktop.

Select an option

Save arthuralvim/13a0464761400975a9da to your computer and use it in GitHub Desktop.
[Django Rest Framework] Serializer for a PrimaryKeyRelatedField where we use a unique key instead of the primary key.
class ModelA(models.Model):
attr1 = models.Charfield()
attr2 = models.Charfield(unique=True)
class ModelB(models.Model):
foreign = models.ForeignKey(ModelA)
class OtherFieldUniqueSerializer(serializers.PrimaryKeyRelatedField):
def from_native(self, value):
try:
return ModelA.objects.get(attr2=value)
except ObjectDoesNotExist:
raise ValidationError(self.error_messages['does_not_exist'])
except (TypeError, ValueError):
raise ValidationError(self.error_messages['incorrect_type'])
def to_native(self, obj):
return obj.attr2
class ModelBSerializer(serializers.ModelSerializer):
foreign = OtherFieldUniqueSerializer('attr2')
class Meta:
model = ModelB
fields = ('id', 'foreign', )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment