开发者

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

开发者 https://www.devze.com 2023-01-13 23:17 出处:网络
I have a simple class: class BlogPost(models.Model): title = models.CharField(max_length=150) ... timestamp = models.DateTimeF开发者_如何学运维ield()

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

精彩评论

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

关注公众号