aleksk
aleksk

Reputation: 711

Django not recognizing field override for Current User in Serializer

I am having an issue in setting the user automatically in django rest framework. In my models.py I have the following:

Models.py

class Space(models.Model):
   creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Serializers.py

class SpaceSerializer(serializers.HyperlinkedModelSerializer):
    creator = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CreateOnlyDefault(serializers.CurrentUserDefault()))

    class Meta:
        model = Space
        fields = '__all__'

The intent is that the creator field will be set during creation through the API. When I issue a POST request to create the model, i get the following error:

"IntegrityError at /api/space/ NOT NULL constraint failed: apiapp_space.creator_id

I assume the serializer is not even using this field override, as when I set null=True in my model, it seems to save correctly with the creator field set to null.

Note that I have also tried using serializers.ModelSerializer.

How can I get django to recognize this field override?

Upvotes: 2

Views: 307

Answers (1)

Carlton Gibson
Carlton Gibson

Reputation: 7386

This is covered in the release notes for v3.8.

For read-only fields you need to pass the value when calling save:

def perform_create(self, serializer):
    serializer.save(creator=self.request.user)

The CreateOnlyDefault is used as the value for the unique_together validation on the model.

This was a breaking change in v3.8, required to allow correct behaviour elsewhere. (Previously read-only fields with a default were considered writable, with the default being used as the written value. Ultimately that turned out to be not a good idea.)

Upvotes: 2

Related Questions