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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With