Unique validation on nested serializer on Django Rest Framework

后端 未结 3 2273
天涯浪人
天涯浪人 2020-12-03 11:09

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

class GenreSerializer(serializers.ModelSerializ         


        
3条回答
  •  旧巷少年郎
    2020-12-03 11:24

    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.

提交回复
热议问题