我有两个模型如下:
class Book(models.Model):
title = models.CharField(max_length=100)
year = models.IntegerField(max_lenght=4)
author = models.ManyToManyField(null=true, blank=true)
class Author(models.CustomUser):
# some fields
现在,我要做的是添加一个
Author
到多个 Book
对象而不迭代书对象列表。Django 的更新方法不支持
ManyToManyField
根据 docs .它说You can only set non-relation fields and ForeignKey fields using this method. To update a non-relation field, provide the new value as a constant. To update ForeignKey fields, set the new value to be the new model instance you want to point to.
所以目前我正在执行以下操作,这是非常低效的,因为我将为每个书对象访问数据库。
author = Author.objects.get(pk=1)
books = Book.objects.filter(**kwargs) # say this returns 100 objects
# each loop here will hit the database making it really inefficient
# for long lists.
for book in books:
book.authors.add(author)
book.save()
我很确定有办法解决这个问题,但我只是无法在文档中找到它。任何帮助,将不胜感激。谢谢
最佳答案
答案在这里:
https://stackoverflow.com/a/10116452/202168
简而言之,(在 Django >= 1.4 中)你可以做一个 bulk_create
在直通模型上,即使您尚未定义自定义直通模型。
关于django - 多对多字段的批量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17364575/