Django ORM查询更新反向多对多字段

Django ORM query to update reverse many to many field

模型看起来像:

class Book(models.Model):
    name = models.TextField(verbose_name='Book Name')

class Author(models.Model):
    name = models.TextField(verbose_name='Author Name')
    Books = models.ManyToManyField(Book)

一本书可以有很多作者 和作者可以写很多书

现在,

  1. 有一个列表如下:
[
{Book_id1:[Author_id1, Author_id2]},
{Book_id2:[Author_id2, Author_id3]},
]

需要在数据库中更新此信息。 如何使用 ORM 以有效的方式完成此操作?

(目前DB可能有 Book_id1 链接到 [Author_id1,Author_id3] 所以更新应该也可以添加 author_id2 和删除 author_id3)

您可以在多对多模型上进行两个查询:

data = [
    {book_id1:[author_id1, author_id2]},
    {book_id2:[author_id2, author_id3]},
]
book_ids = [book_id for datum in data for book_id in datum]

BookAuthor = Author.books.through
BookAuthor.objects.filter(book_id__in=book_ids)<strong>.delete()</strong>
BookAuthor.objects.<strong>bulk_create(</strong>[
    BookAuthor(book_id=bi, author_id=ai)
    for datum in data
    for bi, ais in datum.items()
    for ai in ais
]<strong>)</strong>