使用Django ORM基于最大值获取单个子行

时间:2009-05-31 09:27:45

标签: sql django inner-join django-orm

我有一个模型,“市场”与另一个模型有一对多的关系,“合同”:

class Market(models.Model):
    name = ...
    ...

class Contract(models.Model):
    name= ...
    market = models.ForeignKey(Market, ...)
    current_price = ...

我想以每个的最高价格获取市场对象以及合约。这就是我通过原始SQL实现的方法:

SELECT M.id as market_id, M.name as market_name, C.name as contract_name, C.price 
as price from pm_core_market M INNER JOIN
    (SELECT market_id, id, name, MAX(current_price) as price 
        FROM pm_core_contract GROUP BY market_id) AS C
ON M.id = C.market_id

有没有办法在不使用SQL的情况下实现它?如果有的话,哪个应该是性能优先的?

1 个答案:

答案 0 :(得分:9)

Django 1.1(目前为测试版)为数据库API添加了aggregation支持。您的查询可以这样完成:

from django.db.models import Max, F

Contract.objects.annotate(max_price=Max('market__contract__current_price')).filter(current_price=F('max_price')).select_related()

这将生成以下SQL查询:

SELECT contract.id, contract.name, contract.market_id, contract.current_price, MAX(T3.current_price) AS max_price, market.id, market.name
FROM contract LEFT OUTER JOIN market ON (contract.market_id = market.id) LEFT OUTER JOIN contract T3 ON (market.id = T3.market_id)
GROUP BY contract.id, contract.name, contract.market_id, contract.current_price, market.id, market.name
HAVING contract.current_price =  MAX(T3.current_price)

API使用额外的连接而不是子查询(就像您的查询一样)。很难判断哪个查询更快,特别是在不知道数据库系统的情况下。我建议你做一些基准并做出决定。