Skip to content
Advertisement

How to add data to Many-To-Many field in Django DRF

I’m new to Django DRF, trying to have a sports school project done. I have a model for coaches, classes and students. Here is a stripped version to keep it simple and easy:

JavaScript

In order to list/add students to the class, I’m using the following serializer:

JavaScript

Getting the data is working ok. Also, adding a coach is working fine, what is really giving me a hard time is adding a class member. I’m using the following view:

JavaScript

I’m sending a POST body like:

JavaScript

The problem is no matter how many students in the class, the above will remove them all and put student id 20 instead.

  • How can I keep the current students and only ADD the new id to them?
  • How can I as well remove a student’s id without deleting the whole data in class_members field?

Thanks!

Advertisement

Answer

I would say to define your model in a different way, here is an example –

First define your Class Detail like –

JavaScript

then define your Student such as –

JavaScript

and finally your coach as –

JavaScript

this way you can use the nested feature – now your student is always linked to a class and also your coach is linked to your class.

Now you can say each class can have multiple students and also each class can have multiple coach. Now if Coach is unique per class you can write Coach Modals as –

JavaScript

Editing My answer based on inputs —

to add a new id in manytomany type field first you will have to create a student for eg.

JavaScript

and then do something like

JavaScript

to get the correct instance of classdetail and then do something like –

JavaScript

to add a new student to your manytomany field in ClassDetails

You can customize it according to your needs, hoping this helps you.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement