Reputation: 66320
Goal:
In here I am filtering for deals with the given id and from those I would like to pick the one with the latest date.
contact.deal_set.filter(deal_id=deal_id).aggregate(Max('deal_start_datetime'))
However this only gives back a dictionary with the max date in it. I need the row though. What am I doing wrong?
Upvotes: 2
Views: 357
Reputation: 486
Use the .latest method provide for django query sets.
For example in your particular case:
contact.deal_set.filter(deal_id=deal_id).latest('deal_start_datetime')
Django Documentation: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
Upvotes: 1
Reputation: 53326
Use this
contact.deal_set.filter(deal_id=deal_id).order_by('-deal_start_datetime')
This will sort queryset by deal_start_datetime
in reverse, 0th element is the latest one, you can get it as
latest_contact = contact.deal_set.filter(deal_id=deal_id).order_by('-deal_start_datetime')[0]
Upvotes: 0