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.


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 =

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


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.

Last 5 Articles

All Articles >

  1. Mitigating Risks In Custom Software Development

  2. Container Security to Secure Microservices

  3. Strategic Messaging

  4. URL Shortener in Django

  5. MySQL as Database Option


News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.