开发者

How to Get a Certain Number of Elements from a Django Database

I have a simple class:

class BlogPost(models.Model):
    title = models.CharField(max_length=150)
    ...
    timestamp = models.DateTimeF开发者_如何学运维ield()

How can I get the last five items from the database?

I tried to do this:

posts = BlogPost.objects.<any code>


BlogPost.objects.order_by('-timestamp')[:5]


You use the array-slicing syntax to index into your queryset, and you use the reverse() function to reverse the queryset before indexing, e.g., myQuerySet.reverse()[:5]. See the docs for more details.


I think that ordering by id it's faster than sorting by any other field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜