Q:

Modify object before save and passing it to serializer

I'm trying to set some fields before saving an object that a user wants to insert.  For example, if a user wants to create a new instance, before saving it, I want to set the field owner equal to request.user and then call the create method from the parent.  I've achieved this with the following code:
class ClassView(viewsets. ModelViewSet):
    queryset = ModelClass.objects.all()
    serializer_class = ModelClassSerializer

    def create(self, request, pk = None):
        if ModelClass.objects.filter(pk = request.user.id):
            return Response({'detail' : "This user is already inserted" }, status = status. HTTP_401_UNAUTHORIZED)
        return super(ClassView, self).create(request, pk = None)

    def pre_save(self, obj):
        obj.user_id = ModelClass.objects.get(pk = self.request.user.id)

It could be also that I want to set an attribute of the model according to some calculation with values coming from the POST request (those values are established as fields in the serializer). 
Is the pre_save solution the correct way to go or am I missing something? 
Thanks in advance. 

A:

I would say this is the correct way to go but if you simply want to set the object's user to the current request user, instead of:
obj.user_id = ModelClass.objects.get(pk = self.request.user.id)

...just use:
obj.user = self.request.user

The rest framework pre_save hook is there for your exact requirement but there exists other ones you may find useful.  See http://www.django-rest-framework.org/api-guide/generic-views#genericapiview - under Save / deletion hooks. 
However, if you require this data to be saved on the object instance outside of the rest framework (i.e. additionally within a normal Django view) you will most probably want to use the Django pre_save signal and hook your model up to it.  That way the request user will be stored each time the object is saved, not just via the rest framework: https://docs.djangoproject.com/en/dev/ref/signals/

