且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更新Django中的manytomany字段?

更新时间:2023-12-01 14:34:28

注意此代码将删除坏的georfe作者,以及更新书籍指向正确的作者。如果你不想这样做,那么可以使用 .remove()作为@ jcdyer的答案。

Note: This code will delete the bad 'georfe' author, as well as updating the books to point to the correct author. If you don't want to do that, then use .remove() as @jcdyer's answer mentions.

你可以这样做吗?

george_author = Author.objects.get(name="George")
for book in Book.objects.filter(authors__name="Georfe"):
    book.authors.add(george_author.id)
    book.authors.filter(name="Georfe").delete()

我怀疑,如果你有一个明确的表加入这两个模型, 关键字arg) - 在这种情况下,您将可以直接访问关系表,并且可以在其上执行 .update(id = george_author.id)

I suspect that this would be easier if you had an explicit table joining the two models (with the "through" keyword arg) -- in that case, you would have access to the relationship table directly, and could just do a .update(id=george_author.id) on it.