Reputation: 8301
Let's say I have the following Django model:
class Info(models.Model):
instrument = models.ForeignKey('Instrument')
date = models.DateTimeField()
How can I extract the entry with the newest date for each Instrument ?
Upvotes: 4
Views: 449
Reputation: 410602
If you want to get the latest Info
entry for each instrument, you could do something like this:
latest_notes = []
for instrument in Instrument.objects.all():
latest_note = instrument.info_set.order_by('-date')[0]
latest_notes.append(latest_note)
That may or may not be feasible depending on how many Instrument
records you have.
Upvotes: 0
Reputation: 5382
Try this:
Instrument.objects.all().annotate(max_date=models.Max("info__date"))
It will return a list of all instruments and each intrument will have additional attribute max_date
which contains the latest date for this instrument.
Upvotes: 3