如何在不在 python 中迭代它们的情况下明显地批量更新 django 模型的所有对象?

Posted

技术标签:

【中文标题】如何在不在 python 中迭代它们的情况下明显地批量更新 django 模型的所有对象?【英文标题】:How to distinctly bulk update all objects of a django model without iterating over them in python? 【发布时间】:2013-09-07 22:44:20 【问题描述】:

基本上我们不这样做也能达到同样的效果:

from my_app import models
for prd,count in x.iteritems():
    models.AggregatedResult.objects.filter(product=prd).update(linked_epp_count=count)

? 很明显,x 是一个字典,其中包含与 AggregatedResult 的产品字段相同的键,而“值”是我希望更新的计数。在具有

【问题讨论】:

【参考方案1】:

最简单(但不是最安全)的方法是使用raw sql query。

比如:

for prd,count in x.iteritems():
    from django.db import connection, transaction
    cursor = connection.cursor()

    query = """
        UPDATE table 
        set column = value 
        where condition = condition_value""".format(
        table=AggregatedResult._meta.db_table,
        condition='product',
        condition_value=prd,
        column='linked_epp_count',
        value=count
    )
    cursor.execute(query)
    transaction.commit_unless_managed()

警告:未经测试,极易受到 sql 注入的攻击。使用风险自负

另一种(更安全)的方法是首先将x 的内容加载到临时表中,而不是只发出一个原始查询来更新。假设 x 的临时表是 temp_prod:

update aggregated_result ar
set linked_epp_count=tp.count
from temp_prod tp
where ar.product = tp.product

你如何将数据从x 上传到临时表,我不是很熟练,所以留给你。 :)

【讨论】:

以上是关于如何在不在 python 中迭代它们的情况下明显地批量更新 django 模型的所有对象?的主要内容,如果未能解决你的问题,请参考以下文章