Vladimir Chub
Vladimir Chub

Reputation: 471

get_latest() method in Django for getting few objects

I have a model like this:

from django.core import meta

class Foo(models.Model):
    date = models.DateTimeField()
    name = models.CharField(maxlength=100)

    def __unicode__(self):
        return self.name

    class Meta:
        get_latest_by = 'date'

And I can write

>>> from datetime import datetime
>>> a1 = Foo(name='a1', date=datetime(2012, 12, 18))
>>> a1.save()
>>> a2 = Foo(name='a2', date=datetime(2012, 12, 19))
>>> a2.save()
>>> a3 = Foo(name='a3', date=datetime(2012, 12, 20))
>>> a3.save()
>>> a4 = Foo(name='a4', date=datetime(2012, 12, 21))
>>> a4.save()

Then if I write next I get following result

>>> Foo.objects.latest()
a4

How cat I get the last 3 objects? Something like

>>> Foo.objects.latest(count=3)
a4, a3, a2

Note: I don't have to use sorting, like

>>> Foo.objects.all().order_by('-date')

because the datebase is very large and the query takes a long time.

Upvotes: 0

Views: 367

Answers (1)

atereshkin
atereshkin

Reputation: 706

latest() is merely a shortcut for order_by(model._meta.get_latest_by) so sorting already happens when you use it. There's no other way either. You'll need to use

Foo.objects.order_by('-date')[:3]

If the query is too slow, your options are to either add an index on date field or use id field instead (assuming your are using automatic ids).

Foo.objects.order_by('-id')[:3]

Please note that querysets overload the slice operation, so this will translate to a ...LIMIT 3 in the SQL rather selecting all records and then taking the first 3 on the application side.

Upvotes: 3

Related Questions