4👍
✅
Since you don’t want owner
to be modifiable via your serializer, I’d suggest you to remove the field from the serializer or make it read-only.
You can then set the owner using the serializer’s save
method that allows you to inject additional data.
A good place for this in your example would be the perform_create
method of your ModelViewSet
. For example:
class FooViewSet(viewsets.ModelViewSet):
serializer_class = FooSerializer
permission_classes = [permissions.IsAuthenticated]
queryset = Foo.objects.all()
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
Source:stackexchange.com