django - 多对多字段的批量更新

标签 django many-to-many bulk

我有两个模型如下:

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/

相关文章:

Django选择带有空ManyToManyField的对象

regex - 如何搜索不包含特定字符串的文件

lucene - lucene批量更新策略?

python - 如何在 Django 中获取对象作为字符串?

python - Numpy 作为 django 项目中的库

SQL 计算多对多值还是每次添加新行时都计算?

php - 如何在 MySQL 中获取登录用户不是好友的所有用户?

php - 与学说 2 的关联

php - 缓存 mysql 插入 - 保持数据完整性

mysql - Django 使用外部 mysql DB - 解决问题的最佳方法