django - 如何在Django模型的ManyToManyField中添加id(而不是对象)?

标签 django

模型.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(), 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.

关于django - 如何在Django模型的ManyToManyField中添加id(而不是对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67576431/

相关文章:

html - Django 模板空 div 中插入空格

Django 电子邮件附件发送为 "noname"

python - 具有多对多字段和中间表的模型的 django 查询集中不必要的连接

javascript - 使用javascript函数更改django模板中的元素类

django - Jython,带Sqlite3的Django

Django ImageField 图像不显示

python - 为 Django 表单中的只读字段动态创建 clean_* 方法

python - "Broken"以 UTF-8 编码的 unicode 字符串?

python - 使用本地设置文件从 PyCharm 运行 django 服务器时出错

django - 如何在 Django 中将 CharField 渲染为静态文本?