这个问题是关于RelatedManager.add()的用于将模型对象实例添加到多对一或多对多关系中。为了说明我的问题,假设我有以下两个模型:
class Book(models.Model):
title = models.CharField()
class Author(models.Model):
name = models.CharField()
books = models.ManyToManyField(Book)
现在,对于每个 Author
,我都有一个要添加到关系中的 Book
对象列表。目前,我是这样做的:
book_objects = [
<Book: Harry Potter and the Philosopher's Stone>,
<Book: Harry Potter and the Chamber of Secrets>,
<Book: Harry Potter and the Prisoner of Azkaban>
]
jk_rowling = Author.objects.get(name='J. K. Rowling')
for book in book_objects:
jk_rowling.books.add(book)
jk_rowling.save()
但是,这不是很有效,因为我必须处理数千个要添加到此类关系中的对象,而且需要很长时间。相反,Django 文档 recommends使用多个模型对象作为参数调用 add()
。也就是说,我必须像下面这样:
jk_rowling.books.add(book1, book2, book3)
但我不能这样做,因为我事先不知道添加到关系中的对象数量。我不明白为什么我不能执行以下操作:
jk_rowling.books.add(book_objects)
为什么 add()
不接受一个可迭代对象作为参数?以及如何比分别为每个对象调用 add()
更有效地将大量对象添加到这样的关系中?多谢!
最佳答案
您可以将数组扩展为可变参数:
book_objects = [
<Book: Harry Potter and the Philosopher's Stone>,
<Book: Harry Potter and the Chamber of Secrets>,
<Book: Harry Potter and the Prisoner of Azkaban>
]
jk_rowling = Author.objects.get(name='J. K. Rowling')
jk_rowling.books.add(*book_objects) # <---------------
jk_rowling.save()
关于python - 为什么 RelatedManager.add() 不接受可迭代对象作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923376/