如何在Django中一次将多个对象添加到ManyToMany关系中? [英] How to add multiple objects to ManyToMany relationship at once in Django ?
问题描述
基于Django文档,我应该能够一次传递多个对象以将其添加到多对多关系中,但是我得到了
Based on the Django doc, I should be able to pass multiple objects at once to be added to a manytomany relationship but I get a
* TypeError:不可散列的类型:'list'
* TypeError: unhashable type: 'list'
当我尝试传递列表中的django queryset时.传递Queryset或ValuesListQueryset似乎也失败.有没有比使用for循环更好的方法了?
when I try to pass a django queryset casted in a list. Passing a Queryset or a ValuesListQueryset seems to fail also. Is there a better way than use a for loop ?
推荐答案
使用:object.m2mfield.add(*items)
如 add()
接受任意数量的参数,而不是它们的列表.
add()
accepts an arbitrary number of arguments, not a list of them.
add(obj1, obj2, obj3, ...)
要将该列表扩展为参数,请使用*
To expand that list into arguments, use *
add(*[obj1, obj2, obj3])
附录:
Django不会为每个项目调用obj.save()
,而是使用bulk_create()
.
这篇关于如何在Django中一次将多个对象添加到ManyToMany关系中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!