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
621 views
in Technique[技术] by (71.8m points)

python - Django REST Framework serializer field required=false

from the documentation:

read_only Set this to True to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.

Defaults to False

required Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

Defaults to True.

So I have a model which has a field that's not nullable but I want it to be populated in the pre_save method, so I have set the field to required=False in serializer, but doesn't seem to work. I am still getting error when saving the record.

class FavoriteListSerializer(serializers.ModelSerializer):
    owner = serializers.IntegerField(required=False)
    class Meta:
        model = models.FavoriteList

Update: I have added serializer_class = serializers.FavoriteListSerializer to the ViewSet, now instead of getting This field is required, which I think got past the validation but then I am getting This field cannot be null. I have checked the pre_save method is not being executed, any ideas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yeah, I ran into this issue at some point as well. You need to also update the validation exclusions.

class FavoriteListSerializer(serializers.ModelSerializer):
    owner = serializers.IntegerField(required=False)
    class Meta:
        model = models.FavoriteList

    def get_validation_exclusions(self):
        exclusions = super(FavoriteListSerializer, self).get_validation_exclusions()
        return exclusions + ['owner']

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

...