django - Django ManyToMany 字段的 set() 操作是否清除现有关系?

标签 django python-2.7 django-models django-views django-orm

Django ORM 操作中下面2种情况有区别吗?会有任何性能提升等吗?

obj.manytomanyfield.clear()
obj.manytomanyfield.add(1,2,3,4,5)

obj.manytomanyfield.set([1,2,3,4,5])

最佳答案

来自文档,set()-Django doc

This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once.

这意味着,

obj.manytomanyfield.clear()
obj.manytomanyfield.add(1,2,3,4,5)

等于

obj.manytomanyfield.set([1,2,3,4,5], <b>clear=True</b>)

关于django - Django ManyToMany 字段的 set() 操作是否清除现有关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63412222/

相关文章:

python - Django 中测试信号的基础知识

python - PusherBadRequest 未知 Auth_Key

python - odoo 9 获取当前记录中的字段值

Python 正则表达式转义字符

django - ExtractYear 和 ExtractMonth 在 Django 中返回 None

Django:模型继承:FK & M2M

python - Django:迁移到 NullBooleanField 失败并出现 IntegrityError "contains null values"

python - 如何使用 celery-beat 启动任务?

python - PyAudio - 将stream.read转换为int以获得幅度

python - Django,第一次迁移时auth文件夹下的models.py如何创建初始表?