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?
Yeah, I ran into this issue at some point as well. You need to also update the validation exclusions.
Late Entry to this thread. This issue was fixed in django-rest-framework 2.3.13. Here is the link of the PR.
In case somebody lands here with a similar issue, pay attention to the following attributes along with
required
:allow_blank:
allow_null:
required:
I was straggling to figure out why I was getting a validation error with
required=False
where I had missed theallow_null
attribute.I suppose method .get_validation_exclusions() is now removed. I did not found it in ModelSerializer doc and it did not execute after override (djangorestframework==3.8.2). And i am not the only one facing this problem.
My solution is to just add default value for field which i want to be non-required. It supposed to be fine specifically for situations with pre_save:
You also have to keep in mind that using drf serializers with pre_save signals may cause implicit behavour (i did not check, but it seems to be logical):
pre_save
is called on pre object save (incredible) which (probably) means after serializer validation.