Unique validation on nested serializer on Django Rest Framework
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping
--
Chapters
00:00 Unique Validation On Nested Serializer On Django Rest Framework
00:44 Accepted Answer Score 41
01:13 Answer 2 Score 2
01:53 Answer 3 Score 2
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/3843...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #rest #djangorestframework #djangoserializer
#avk47
ACCEPTED ANSWER
Score 41
You should drop the unique validator for the nested serializer:
class GenreSerializer(serializers.ModelSerializer):
class Meta:
fields = ('name',) #This field is unique
model = Genre
extra_kwargs = {
'name': {'validators': []},
}
You may want to print your serializer before to make sure you don't have other validators on that field. If you have some, you'll have to include them in the list.
Edit: If you need to ensure the uniqueness constraint for creation, you should do it in the view after the serializer.is_valid has been called and before serializer.save.
ANSWER 2
Score 2
This happens because the nested serializer (GenreSerializer) needs an instance of the object to validate the unique constraint correctly (like put a exclude clause to the queryset used on validation) and by default, a serializer will not pass the instance of related objects to fileds the are nested serializers when runs the to_internal_value() method. See here
Another way to solve this problem is override the get_fields() method on parent serializer and pass the instance of related object
class BookSerializer(serializers.ModelSerializer):
def get_fields(self):
fields = super(BookSerializer, self).get_fields()
try: # Handle DoesNotExist exceptions (you may need it)
if self.instance and self.instance.genre:
fields['genre'].instance = self.instance.genre
except Genre.DoesNotExist:
pass
return fields
ANSWER 3
Score 2
Together than remove the UniqueValidator using
'name': {'validators': []}
You need to validate the Unique entry yourself ignoring the current object, for not get an 500 error when another person try to save the same name, something like this will work:
def validate_name(self, value):
check_query = Genre.objects.filter(name=value)
if self.instance:
check_query = check_query.exclude(pk=self.instance.pk)
if self.parent is not None and self.parent.instance is not None:
genre = getattr(self.parent.instance, self.field_name)
check_query = check_query.exclude(pk=genre.pk)
if check_query.exists():
raise serializers.ValidationError('A Genre with this name already exists
.')
return value
A method validate_<field> is called for validate all your fields, see the docs.