Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.DateTimeField()

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

I tried to do this:

posts = BlogPost.objects.<any code>
like image 941
Oleg Kovalov Avatar asked Feb 27 '23 09:02

Oleg Kovalov


1 Answers

BlogPost.objects.order_by('-timestamp')[:5]
like image 118
awithrow Avatar answered Feb 28 '23 22:02

awithrow