Home > Blockchain >  Django Rest Framework ignores default value
Django Rest Framework ignores default value

Time:12-03

Any idea why does Django Rest Framework ignore default values?

class MyClass(models.Model):
    some_field = models.CharField(default='Yes')

class MyClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyCLass
        fields = ['some_field']

class MyClassListCreateAPIView(ListCreateAPIView):
    queryset = MyClass.objects.all()
    serializer_class = MyClassSerializer

When I send {'some_field': None} /null/something like this. I always get:

Bad Request: /myurl/
[02/Dec/2022 16:44:59] "POST /myurl/ HTTP/1.1" 400 114

When changed to:

class MyClass(models.Model):
        some_field = models.CharField(default='Yes', blank=True, null=True)

it works but always sets the NULL value. Is this expected behaviour? Should I change the mechanics of my POST request to include changing value to default when user doesn't provide one?

CodePudding user response:

I believe this is a minor misconception.

Posting {'some_field': None} to your API is informing your Serializer to manufacture a MyClass instance with some_field set to None- not to use the default. It is not using the default value- because you're instantiating it with a value of None.

If you want to use the default value on your model- you need to clean/remove the some_field value during serializer Validation so that the create() call does not have this field present- and the default will be used.

Should I change the mechanics of my POST request to include changing value to default when user doesn't provide one?

This would certainly be a solution and would work. But unless this is well documented- outside consumers of your API may notice the same odd behavior.

CodePudding user response:

I don't think is the main problem but: are you setting the max_length required option in your MyClass model definition? If it's not needed, why it's not required in this case? In the fields types' documentation is supposed to be required.

  • Related