大量更新许多领域 [英] bulk update for many to many fields

查看:65
本文介绍了大量更新许多领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种模型:

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 对象,而无需遍历书籍对象列表.

Now, what I am looking to do is add an Author to multiple Book objects without iterating over the list of book objects.

Django的更新方法不按照

Django's update method does not support ManyToManyField as per docs. It says

您只能使用此方法设置非关系字段和ForeignKey字段.要更新非关系字段,请提供新值作为常量.要更新ForeignKey字段,请将新值设置为要指向的新模型实例.

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.

因此,我目前正在执行以下操作,效率很低,因为我将访问每个书本对象的数据库.

so currently I am doing the following which is highly inefficient as I'll be hitting the database for each book object.

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()

我很确定有办法解决这个问题,但我只是无法在文档中找到它.任何帮助,将不胜感激.谢谢

I am pretty sure there is a way around this but I am just not able to find it in the docs. Any help would be appreciated. Thanks

推荐答案

答案在这里:
https://stackoverflow.com/a/10116452/202168

简而言之,(即使在Django> = 1.4中)您也可以在直通模型上执行 bulk_create ,即使您尚未定义自定义直通模型.

In short, (in Django >= 1.4) you can do a bulk_create on the through model, even if you haven't defined a custom through model.

这篇关于大量更新许多领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆