Django Rest Framework is a life saver, packed with generic views and tons of features. Designed to solve the day to day application the in-box features does many thing but there are a few which it cannot. One of them is assigning users to a object being created, assign a value to many t0 many relation and more.
Django Rest Framework Documentation does provides a method on Associating Snippets with Users that is good and will solve the problem, but it didn’t work for me.
The object being created had a field which associates the user which is solved by the above solution but it had a second field which includes a Many to Many relation to another model. M2M relations cannot be assigned as above so I had to tweak a bit and fix it.
Solution is to use
def perform_create() inside the
ModelViewSet, the function is invoked by
CreateModelMixin when a new object instance is being saved. Which is idea time to assign a m2m relation.
queryset = Property.objects.filter()
serializer_class = PropertySerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
property = serializer.save(owner=self.request.user)
The field user is used to keep record of users who have access to the object.