'Filter queryset by subquery on two conditions
I need to filter SomeModel queryset on max date by groups (user field). The Model looks like:
class SomeModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(default=date.today)
...
I've already created some kind of subquery:
from django.db.models import Max
subquery = (SomeModel.objects
.all()
.values('user')
.annotate(latest_date=Max('date')))
So I want to use this subquery to filter SomeModel queryset on two conditions:
# pseudocode
SomeModel.objects.filter(user==subquery.user and time==subquery.latest_time)
Is it possible at all or my approach is wrong?
Solution 1:[1]
I found out that the result I wanted to get could be achieved this way:
SomeModel.objects.order_by('user', 'date').distinct('user')
It's not an answer on initial question but it could help someone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jeldzinski |
