Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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]
like image 213
Jasmeet Pabla Avatar asked Oct 17 '25 03:10

Jasmeet Pabla


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.

like image 71
NKSM Avatar answered Oct 18 '25 16:10

NKSM


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 
like image 43
OzanCanPaksoy Avatar answered Oct 18 '25 17:10

OzanCanPaksoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!