Associating Many to Many Relation in DJango Rest Framework

Add an entry to a Many to Many field when an object is created using API with Django Rest Framework.

Advert

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.


class PropertyViewSet(viewsets.ModelViewSet):
 queryset = Property.objects.filter()
 serializer_class = PropertySerializer
 permission_classes = (permissions.IsAuthenticated,)

 def perform_create(self, serializer):
  property = serializer.save(owner=self.request.user)
  property.user.add(self.request.user)

The field user is used to keep record of users who have access to the object.

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.