Doug Smith
Doug Smith

Reputation: 580

Django queryset return the newest of field choices

I would like the return a queryset that is comprised of the newest (date) objects for each choice of a field name. I can do it by iterating over an ordered queryset and then progressively removing older objects with exclude(). I'm wondering if this could be done using latest(). I don't know how to run latest with each unique value of name.

I don't have a lot of experience with django, I'm worried that my working code below would be slow/expensive. It groups the dogs by name, then orders it by date, then systematically removes older dates.

class Dog(models.Model):
    # names = husky, poodle, lab, etc
    name = models.CharField(max_length=20)
    age = models.IntegerField()
    datemade = models.DateField(default=date.today) 

views.py
ad = Dog.objects.all().order_by('name', 'datemade')
    n=0
    while n < (len(ad)-1):
        if ad[n].name==ad[n+1].name and ad[n].datemade<=ad[n+1].datemade:
            ad = ad.exclude(id=ad[n].id)
            print(ad)
            n=n-1
        n=n+1

Upvotes: 1

Views: 61

Answers (1)

lucutzu33
lucutzu33

Reputation: 3710

Dog.objects.all().order_by('name', '-datemade').distinct('name') .

Note that it works only with postgresql.

Upvotes: 2

Related Questions