模型.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)
我需要将员工 ID(而不是员工对象)保存在“部门”模型的“员工”ManyToManyField 中。如何做到这一点?
views.py:
dept = Department(name=name)
dept.save()
employee_ids = [1,2]
最佳答案
我们可以使用方法add
(Django Docs):
Adds the specified model objects to the related object set.
dept = Department.objects.create(name=name)
dept.employee.add(<b>*[1, 2]</b>)
或者方法set
(Django Docs):
Replace the set of related objects
dept.employee.set(<b>[1, 2]</b>)
Note that
add()
,create()
,remove()
,clear()
, andset()
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.
关于django - 如何在Django模型的ManyToManyField中添加id(而不是对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67576431/