26

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!!

Ignacio D. Favro
  • 403
  • 1
  • 4
  • 10

3 Answers3

40

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.

Linovia
  • 19,812
  • 4
  • 47
  • 48
  • Thank you a lot! But if i need the validation in the nested serializer when i use it for save Genre instances? is there a way to check only if i creating a Genre instance and not if a creating a Book instance? Thank you again! – Ignacio D. Favro Jul 18 '16 at 13:59
  • 1
    That should be part of a second validation step - say in the create/update part by raising ValidationError. – Linovia Jul 18 '16 at 23:03
  • That's was really helpfull! Thank you a lot! – Ignacio D. Favro Jul 19 '16 at 13:45
  • Also see [this](https://medium.com/django-rest-framework/dealing-with-unique-constraints-in-nested-serializers-dade33b831d9) and [this](https://github.com/encode/django-rest-framework/issues/2996) for more info. – a2f0 Nov 10 '17 at 00:56
  • Is it best practice to validate the uniqueness in the view? If I use viewsets, should I put the validation in `create` or `perform_create`? I'd really like to see a simple example using `UniqueValidator`. – cezar Jan 15 '18 at 12:02
  • 1
    `perform_create` is a good match because you'd avoid duplicating code from view set's `create`. Could also be done within the serializer's `create`/`update` though I don't like the idea of raising validation errors from there. Finally you could also make the serializer's save a no-op and use a business layer to perform the last mile validation and deal with the associated logic. – Linovia Jan 15 '18 at 12:29
  • Then `perform_create` should be implemented in `BookViewSet`, although it is about validating the `Genre`. This doesn't look very clean to me. What is your opinion on that? – cezar Jan 15 '18 at 13:16
  • This is already answered and feel free to open another question for further explanation. – Linovia Jan 15 '18 at 13:31
  • @Linovia Thank you! I opened another question: https://stackoverflow.com/questions/48267017/drf-validate-nested-serializer-data-when-creating-but-not-when-updating – cezar Jan 16 '18 at 08:07
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
Lucas Weyne
  • 1,107
  • 7
  • 17
  • You are setting always the current genre object. If we are in an update case this might have changed. So only the "old" object will be validated. Thats a bug, I guess. – Ron Aug 31 '20 at 15:06
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.

Lucas Paim
  • 417
  • 4
  • 13