0

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.

4

1 回答 1

3

latest()只是一种快捷方式,order_by(model._meta.get_latest_by)因此在您使用它时已经进行了排序。也没有别的办法。你需要使用

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

如果查询太慢,您可以选择在日期字段上添加索引或使用id字段代替(假设您使用的是自动 ID)。

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

请注意,查询集会重载切片操作,因此这将转换为...LIMIT 3SQL 中的 a,而不是选择所有记录,然后在应用程序端获取前 3 个记录。

于 2012-12-18T06:54:32.537 回答