Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique validation on nested serializer on Django Rest Framework

Tags:

I have a case like this, where you have a custom nested serializer relation with a unique field. Sample case:

class GenreSerializer(serializers.ModelSerializer):      class Meta:         fields = ('name',) #This field is unique         model = Genre  class BookSerializer(serializers.ModelSerializer):      genre = GenreSerializer()      class Meta:         model = Book         fields = ('name', 'genre')      def create(self, validated_data):         genre = validated_data.pop('genre')         genre = Genre.objects.get(**genre)         return Book.objects.create(genre=genre, **validated_data) 

The problem: When i try to save a json object like {"name":"The Prince", "genre": {"name": "History"}} DRF try to validate the genre object unique constraint and if "History" exists throw me an exception because a genre with name "History" must be unique, and that's true but i just trying to relate the object and not create together.

Thank you a lot!!

like image 975
Ignacio D. Favro Avatar asked Jul 18 '16 13:07

Ignacio D. Favro


People also ask

How does Django validate data in serializer?

Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class. With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class.

How do I know if my serializer is valid?

We can validate the serializer by calling the method " is_valid() ". It will return the boolean(True/False) value. If the serializer is not valid then we can get errors by using the attribute "errors".

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

How does serializer work on Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

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.

like image 164
Linovia Avatar answered Sep 23 '22 18:09

Linovia