我的项目中有 2 个模型:
class Currency(models.Model):
title = models.CharField(max_length=100, unique=True)
value = models.FloatField()
class Good(models.Model):
name = models.CharField(max_length=100)
slug = SlugField(max_length=100, unique=True)
cost_to_display = models.IntegerField(default=0)
cost_in_currency = models.IntegerField()
currency = models.ForeignKey(Currency)
这种模型的想法是通过价格加快搜索速度,并且所有商品都以一种货币表示。 因此,我需要一些钩子(Hook)来更新所有商品,以防汇率更新。
在原始 SQL 中,它看起来像这样
mysql> update core_good set cost_to_display = cost_in_currency * (select core_currency.value from core_currency where core_currency.id = currency_id ) ;
Query OK, 663 rows affected (0.10 sec)
Rows matched: 7847 Changed: 663 Warnings: 0
工作速度相当快。虽然我尝试在 django admin 中实现相同的功能(使用 bulk-update ):
def save_model(self, request, obj, form, change):
"""Update rate values"""
goods = Good.objects.all()
for good in goods:
good.cost_to_display = good.cost_in_currency * good.currency.value
bulk_update(goods)
obj.save()
通过这种方式通过 django admin 更新所有记录最多需要 20 分钟。
我做错了什么?更新所有价格的正确方法是什么?
最佳答案
这纯粹是未经测试的,但在我看来这是一种工作:
from django.db.models import F
Good.objects.all().update(cost_to_display=F('cost_in_currenty') * F('currency__value'))
即使您调用了bulk_update
,您仍然循环遍历所有商品,这就是您的进程缓慢的原因。
编辑:
这不起作用,因为 F()
不支持连接字段。可以使用原始查询来完成。
关于python - 通过计算在 django 中批量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956673/