Created
September 7, 2014 22:10
-
-
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.
This file contains hidden or 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 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