mommermi mommermi - 5 months ago 19
Python Question

How to automatically fill-in model fields in Django rest_framework serializer?

Let's assume I have a model like this:

class Data(models.Model):
a = models.CharField()
b = models.CharField()
c = models.IntegerField()


I would like to setup a serializer in such a way that it automatically fills in field
c
and it is not required for a POST. I tried to overwrite the
create
function of the serializer, but it doesn't work:

class DataSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Data
fields = ('a', 'b')

def create(self, validated_data, **kwargs):
Data.objects.c = 5
return Data.objects.create(**validated_data)


However, if I try this, I end up with an
IntegrityError: NOT NULL constraint failed: model_data.c
. What is the syntax that I have to use here?

Answer Source

In your code Data.objects.c = 5 does nothing.

If you want to set this value yourself use validated_data['c'] = 5 or Data.objects.create(c=5, **validated_data) (just not both at the same time).