Selecting one child row based on maximum value using Django ORM

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?

+3
source share
1 answer

Django 1.1 ( ) aggregation API . :

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 (, ). , , , . .

+9

Source: https://habr.com/ru/post/1709466/


All Articles