seawolf
seawolf

Reputation: 2195

Django REST Framework substituting 'null' for 0 in IntegerField

I have a model in Django with an IntegerField:

class MyModel(models.Model):
    number = models.IntegerField(default=0)

I use Django REST Framework's model serializer:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel

The JSON that is created by the REST framework is:

{
    "number": null
}

The problem is that this fails validation if I just post it back exactly as received. What do I change in order to have the received JSON object use 0 instead of null for an object?

Upvotes: 6

Views: 8864

Answers (2)

kjpc-tech
kjpc-tech

Reputation: 570

I created this Serializer field to render null values as 0.

from rest_framework import fields, serializers

class IntegerDefaultField(fields.IntegerField):
    def get_attribute(self, instance):
        attibute = super().get_attribute(instance)
        if attibute is None and self.default != fields.empty:
            attibute = self.default
        return attibute

class ExampleSerializer(serializers.Serializer):
    number = IntegerDefaultField(default=0)

Overriding to_representation did not work for me since the Serializer doesn't call that method when the field value is None.

Upvotes: 0

miki725
miki725

Reputation: 27861

As Mark Galloway commented, null will appear if you have null data in your database. You can solve this by either by changing the validation login in the serializer:

class MySerializer(serializers.ModelSerializer):
    number = models.IntegerField(initial=0, allow_null=True)
    class Meta:
        model = MyModel

or by changing how data is serialized back to the user:

class MyIntegerField(serializers.IntegerField):
    def to_representation(self, value):
        if value is None:
            return 0
        return super(MyIntegerField, self).to_representation(value)

class MySerializer(serializers.ModelSerializer):
    number = MyIntegerField(initial=0)
    class Meta:
        model = MyModel

Upvotes: 7

Related Questions