在Django的ManyToMany关系中按ID添加对象 [英] Add an object by id in a ManyToMany relation in Django
问题描述
Django的ManyToMany字段可以使用my_field.add(my_instance)
填充,但据我了解,实际上只需要my_instance.id
即可执行相应的SQL查询.
Django's ManyToMany field can be populated using my_field.add(my_instance)
, but as I understand it only my_instance.id
is actually needed to perform the corresponding SQL query.
如果要通过其ID添加对象,可以使用my_field.add(MyModel.objects.get(id=id))
,但这将生成两个查询,而不是一个查询.如何避免这种额外的查询?
If I want to add an object by its id, I can use my_field.add(MyModel.objects.get(id=id))
, but this will generate two queries instead of one. How can I avoid this extra query?
推荐答案
Although the documentation of the add
method does not mention it, you can actually pass directly an id to it, like this:
my_instance.add(id)
当然,这仅在将主键用作关系的标识符(默认行为)时有效.
Surely, this only works when the primary key is used as the identifier for the relation (the default behaviour).
这篇关于在Django的ManyToMany关系中按ID添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!