How to add id (instead of object) in ManyToManyField of Django model?

Viewed 645

models.py :

class Employee(models.Model):
   name = models.CharField(max_length=100)

class Department(models.Model):
   name = models.CharField(max_length=100)
   employee = models.ManyToManyField(Employee, null=True, blank=True)

I need to save employee ids (instead of employee object) in 'employee' ManyToManyField of 'Department' model. How to do that?

views.py:

dept = Department(name=name)
dept.save()
employee_ids = [1,2]
2 Answers

We can use method add (Django Docs):

Adds the specified model objects to the related object set.


dept = Department.objects.create(name=name)
dept.employee.add(*[1, 2])

Or method set(Django Docs):

Replace the set of related objects


dept.employee.set([1, 2])

Note that add(), create(), remove(), clear(), and set() all apply database changes immediately for all types of related fields. In other words, there is no need to call save() on either end of the relationship.

I think this question is unclear what exactly are you trying to do ? If you want to create a relation between department and employee on the database level django does that for you

on your current structure the relation and is like

id|department_id|user_id
--|-------------|-------
 1|     3       |  2 
Related