Unique validation on nested serializer on Django Rest Framework

后端 未结 3 2289
天涯浪人
天涯浪人 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:13

    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_ is called for validate all your fields, see the docs.

提交回复
热议问题