Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

python - Unique validation on nested serializer on Django Rest Framework

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...