Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework serializer field is required even when required=False

I have a model like this

class FalseUserAnswer(BaseModel):
    question = models.ForeignKey(TrueOrFalseQuestion, on_delete=models.CASCADE)
    user_question = models.ForeignKey(TrueOrFalseUserQuestion, on_delete=models.CASCADE, null=True)
    answer = models.ForeignKey(FalseAnswer, on_delete=models.CASCADE)

the problem is one old version of my frontend does not send user_question while the newer one does. So, I want to accept an object that does not have the field at all (it will not be null, or None or nothing, just won't be in the request).

I tried to do something like this in my serializer

class FalseUserAnswerSerializer(serializers.ModelSerializer):
    # Allows null for version < 1.18 of the app. Might be removed in the future.
    user_question = serializers.PrimaryKeyRelatedField(queryset=TrueOrFalseUserQuestion.objects.all(), required=False, allow_null=True)

    class Meta:
        model = FalseUserAnswer
        fields = ['id', 'creator', 'question', 'user_question', 'answer', 'type']

But I still get

"error": {
        "user_question": [
            "This field is required."
        ]
}

Django REST framework version is 3.8.2

Any help is appreciated, thanks for your time.

like image 594
Florian Thuin Avatar asked Jul 19 '18 15:07

Florian Thuin


1 Answers

I read the source code, and apparently to get the behaviour I want, I must set the default value to None. Does not makes sense since I believed it would be the fallback value once I say required=False (and the database field should be filled with NULL).

So previously my code was

user_question = serializers.PrimaryKeyRelatedField(queryset=TrueOrFalseUserQuestion.objects.all(), required=False, allow_null=True)

The working version is

user_question = serializers.PrimaryKeyRelatedField(queryset=TrueOrFalseUserQuestion.objects.all(), required=False, allow_null=True, default=None) 
like image 93
Florian Thuin Avatar answered Oct 22 '22 09:10

Florian Thuin