我正在建立一个库存跟踪应用程序,需要每分钟使用当前价格自动更新Stock模型(从Google财经中提取)。我需要知道如何以更有效的方式做到这一点,因为有数千条记录,而且我目前的方法非常慢且效率低。
#models.py
class Stock(models.Model):
ticker = models.CharField(max_length=200)
current_price = models.DecimalField(max_digits=20, decimal_places=5)
以下脚本每分钟运行一次crontab
#script set to run on a crontab
from takestock.stock_getter import get_quotes
from takestock.models import Stock
class Command(BaseCommand):
help = 'Gathers current stock prices from Google Finance using stock_getter script (imported) and updates all stocks in the database to reflect the current stock price.'
def get_stock_dict(self):
all_stocks = Stock.objects.all()
stock_names = []
for single_stock in all_stocks:
stock_names.append(str(single_stock.ticker))
stock_values = get_quotes(stock_names) #a list of values which corresponds to the list of names
stock_dict = dict(zip(stock_names, stock_values)) #stock tickers and stock values zipped into dict (see below)
return stock_dict
#stock_dict looks like: {'GOOG': '73.84', 'AAPL': '520.34'}
def handle(self, *args, **options):
stock_dict = self.get_stock_dict()
for ticker, value in stock_dict.items():
stock_obj = Stock.objects.get(ticker=ticker)
stock_obj.current_price = value
stock_obj.save()
这种方法有效,但速度非常慢,我认为这是非常数据库密集型的。有没有更好的方法来实现这一目标?感谢。