I have a Market model that has a one-to-many relationship to another Contract model:
class Market(models.Model):
name = ...
...
class Contract(models.Model):
name= ...
market = models.ForeignKey(Market, ...)
current_price = ...
I would like to receive Market objects together with a contract with a maximum price of each. Here is how I would do it through raw 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
Is there any way to implement this without using SQL? If so, which one should be preferred in terms of performance?
source
share