Fabian
Fabian

Reputation: 5650

Set creator automatically with DjangoRestFramework

I have a model with a creator field. I want this field to be initialized to the person that created the model instance and not be modifyable later on.

The creator field looks like this:

creator = models.ForeignKey(User)

And in the DRF HyperlinkedModelSerializer I have this:

read_only_fields = ('creator',)

Now the problem is I of course can't create new instances anymore since the creator field is not set. how can I achieve that?

One possible solution seems to be this

def create(self, validated_data):
    validated_data['creator'] = self.context['request'].user
    return models.MyModel.objects.create(**validated_data)

Is this the dry way to do it?

Upvotes: 1

Views: 414

Answers (1)

Michael Rigoni
Michael Rigoni

Reputation: 1966

You can combine CreateOnlyDefault and CurrentUserDefault and define creator as read_only with a default value on your Serializer:

creator = serializers.HyperlinkedRelatedField(
    read_only=True,
    default=serializers.CreateOnlyDefault(serializers.CurrentUserDefault()),
    view_name=...
)

This is my preferred way of doing this as you see directly from the Serializer definition the creator field is treated specially.

Upvotes: 3

Related Questions