Extract latest entry from a model in Django
Let's say I have th开发者_开发百科e 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 ?
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.
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.
精彩评论