Reputation: 23
I'm performing two queries to obtain all of the latest matches as shown below. Is there a more efficient way to retrieve all match objects that have the same latest date?
class Match(models.Model):
team = models.CharField()
round_date = models.DateField()
date = Match.objects.latest('round_date').round_date
Match.objects.filter(round_date=date)
Upvotes: 1
Views: 134
Reputation: 476574
You can use a Subquery
[Django-doc] here:
from django.db.models import Subquery
maximal = Match.objects.order_by('-round_date').values('round_date')[:1]
Match.objects.filter(round_date=Subquery(maximal))
which will perform a single query:
SELECT match.id, match.round_date
FROM match
WHERE match.round_date = (
SELECT U0.round_date
FROM match U0
ORDER BY U0.round_date DESC
LIMIT 1
)
The maximal
query is thus - unless you would of course "consume" it - not evaluated, but is used to construct a subquery.
In case the field on which you order can be NULL
able, this is not the case here, I advise to use an .order_by(F('round_date').desc(nulls_last=True))
.
Upvotes: 2