Nicu Surdu
Nicu Surdu

Reputation: 8301

Extract latest entry from a model in Django

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

Answers (2)

mipadi
mipadi

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

Andrey Fedoseev
Andrey Fedoseev

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

Related Questions