Django REST Framework serializer field required=false

PythonDjangoRestDjango Rest-Framework

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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']

Solution 2 - Python

Late Entry to this thread. This issue was fixed in django-rest-framework 2.3.13. Here is the link of the PR.

You use it like this in your case:

    class Meta:
        model = models.FavoriteList
        optional_fields = ['owner', ]

Solution 3 - Python

In case somebody lands here with a similar issue, pay attention to the following attributes along with required:

allow_blank:

> If set to True then the empty string should be considered a valid value.

allow_null:

> Normally an error will be raised if None is passed to a serializer field.

required:

> Normally an error will be raised if a field is not supplied during deserialization.

I was straggling to figure out why I was getting a validation error with required=False where I had missed the allow_null attribute.

Solution 4 - Python

In 2020, for DRF 3.12.x, the approach that I prefer the approach that relies on Serializer's extra_kwargs.

So assuming your

class FavoriteListSerializer(serializers.ModelSerializer):
    owner = serializers.IntegerField(required=False)
    class Meta:
        model = models.FavoriteList
        fields = ["owner"]  # and whatever other fields you want to expose
        extra_kwargs = {"owner": {"required": False, "allow_null": True}}

Solution 5 - Python

If you have unique_together constraint on one of the fields you are trying to set required=False you need to set validators=[] in serializers Meta like

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

Here is the original answer

Solution 6 - Python

You can also do this:

class ASerializer(serializers.HyperlinkedModelSerializer): 
    owner = serializers.HiddenField(default=serializers.CurrentUserDefault())

    ...

As referred here: https://www.django-rest-framework.org/api-guide/validators/#advanced-field-defaults There you can also find the case when you also wanna let the view show owner

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames LinView Question on Stackoverflow
Solution 1 - PythonKevin StoneView Answer on Stackoverflow
Solution 2 - PythonPankaj SinghalView Answer on Stackoverflow
Solution 3 - PythonWtowerView Answer on Stackoverflow
Solution 4 - PythonIllya GerasymchukView Answer on Stackoverflow
Solution 5 - PythonVaghinakView Answer on Stackoverflow
Solution 6 - PythonMicheleView Answer on Stackoverflow