You have multiple methods for doing this.
The easiest method is the one suggested by the documentation (https://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save) :
Passing additional attributes to .save()
Sometimes you'll want your view code to be able to inject additional
data at the point of saving the instance. This additional data might
include information like the current user, the current time, or
anything else that is not part of the request data.
You can do so by including additional keyword arguments when calling
.save(). For example:
serializer.save(owner=request.user)
Or you can overwrite the .create()
method of your serializer, and use self.context
:
class FooSerializer(serializers.Serializer):
bar = serializers.CharField()
created_by = serializers.IntegerField(read_only=True) # FK
def create(self, validated_data):
created_by = get_object_or_404(User, user=self.context["request"].user)
foo = Foo()
foo.bar = validated_data["bar"]
foo.created_by = created_by
foo.save()
return foo