简体   繁体   English

使用Django连接和遍历外键表

[英]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_stockmyapp_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.

相关问题 django admin中的反转外键关系 - Inverted foreign-key relation in django admin 迭代抽象django模型中所有与外键相关的子项 - Iterating through all foreign key related children of an abstract django model 试图在 Django 中的模型表之间建立一个关系。但是我在插入值时出错|外键项目必须是一个实例 - Trying to establish a realtion Between model tables in Django.but iam getting error while insering values |foreign-key item must be an instance django在视图中获取外键模型并以html显示 - django Get foreign-key model in view and show in html Django-使用外键和多种形式注册用户 - Django- Registering user with foreign-key and multiple forms django:外键集中的对象的唯一名称 - django : unique name for object within foreign-key set Django 查询集外键 3 个表 - Django queryset foreign key 3 tables SQLAlchemy + SQLite中一列上具有多个外键关系的关联表 - Association tables with multiple foreign-key relationships on one column in SQLAlchemy + SQLite Django:每次外键与所述模型相关联时更新模型字段? - Django: Update Model-Field everytime a Foreign-Key is associated with said model? 如何使用django-autocomplete-light以表格形式返回具有有效值的外键? - How to use the django-autocomplete-light to return the foreign-key with a valid value in the form?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM