【发布时间】:2016-04-29 15:24:00
【问题描述】:
我的项目中有 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)
这种模式的想法是加快按价格搜索并以一种货币提供所有商品。 因此,我需要一些挂钩来更新所有商品,以防汇率更新。
在原始 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 分钟。
我做错了什么?更新所有价格的正确方法是什么?
【问题讨论】:
标签: python mysql django django-orm