I wanna get the first 4 Blog objects associated with the Blog Model.
I tried this:
#views
blog_list = blog.objects.all().order_by("id")[:4]
This works until I create more than 4 blog objects, and then the result doesn't include the recently created objects rather it gets stuck with the first 4 objects.
CodePudding user response:
You always get the first four, since you get the Blog
items with the smallest primary key, which will be (approximately) the "oldest" four.
You can order in descending order with:
blog_list = blog.objects.order_by('-id')[:4]
The primary key however does not fully guarantee that this is the order in which objects are created, and is thus not a safe way to do this.
You can also work with a "random order", although this is often computationally expensive:
blog_list = blog.objects.order_by('?')[:4]
or use the that is determined by the ordering
option [Django-doc], or if there is no such option by the order that the database uses (which can be
any order):
blog_list = blog.objects.all()[:4]
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
toblog
Blog
.