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.
latest()is merely a shortcut fororder_by(model._meta.get_latest_by)so sorting already happens when you use it. There’s no other way either. You’ll need to useIf the query is too slow, your options are to either add an index on date field or use
idfield instead (assuming your are using automatic ids).Please note that querysets overload the slice operation, so this will translate to a
...LIMIT 3in the SQL rather selecting all records and then taking the first 3 on the application side.