我有一个模型“市场”,它与另一个模型“合同”有一对多的关系:
class Market(models.Model):
name = ...
...
class Contract(models.Model):
name= ...
market = models.ForeignKey(Market, ...)
current_price = ...
我想获取 Market 对象以及每个合约的最高价格。这就是我通过原始 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 的情况下实现这一点?如果有,在性能方面应该首选哪一个?