[英]Joining and iterating through foreign-key tables with Django
I have the following 2 Django models: 我有以下2个Django模型:
from django.db import models
class Stock(models.Model):
symbol = models.CharField(db_index=True, max_length=5, null=False, editable=False, unique=True)
class PriceHistory(models.Model):
stock = models.ForeignKey(Stock, related_name='StockHistory_stock', editable=False)
trading_date = models.DateField(db_index=True, null=False, editable=False)
price = models.DecimalField(max_digits=12, db_index=True, decimal_places=5, null=False, editable=False)
class Meta:
unique_together = ('stock', 'date')
Obviously this leads to two DB tables being created: myapp_stock
and myapp_pricehistory
. 显然,这导致创建了两个数据库表: myapp_stock
和myapp_pricehistory
。 These tables have 2 and 4 columns respectively. 这些表分别具有2列和4列。 The first table contains thousands of rows. 第一个表包含数千行。 The second table contains millions of rows. 第二个表包含数百万行。
I want to join the tables, sort the resultant rows and iterate through these rows one-by-one print them. 我想加入表,对结果行进行排序,并逐行遍历这些行以打印它们。 This is how I plan to do it: 我打算这样做:
for i in PriceHistory.object.all().order_by('stock__symbol', 'trading_date'):
print '{} {}: {}'.format(i.stock.symbol, i.trading_date, i.price)
Is this the most efficient way to do it to minimize calls to the database? 这是最小化对数据库的调用的最有效方法吗? I want it to run only one SQL query. 我希望它仅运行一个SQL查询。 I'm concerned that the above code will run a separate query of the myapp_stock
table each time it goes through the for loop. 我担心上述代码每次通过for循环时都会对myapp_stock
表运行一个单独的查询。 Is this concern valid? 这种担忧有效吗? If so, how to avoid that? 如果是这样,如何避免这种情况?
Basically, I know the ideal SQL would look something like this. 基本上,我知道理想的SQL看起来像这样。 How can I get Django to execute something similar?: 我如何让Django执行类似的操作?:
select
s.symbol,
ph.trading_date,
ph.price
from
myapp_stock as s,
myapp_pricehistory as ph
where
ph.stock_id=s.id
order by
s.symbol asc,
ph.trading_date asc
You need to use select_related
to avoid making an additional query for each item in the loop: 您需要使用select_related
以避免对循环中的每个项目进行额外的查询:
histories = PriceHistory.objects.all().select_related('stock')\
.order_by('stock__symbol', 'trading_date')
for i in histories:
print '{} {}: {}'.format(i.stock.symbol, i.trading_date, i.price)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.