Issue
I'm working on blog project & I have 'Last posts' section for posts in car category i want to get last 3 object of my model from db and send with context to template.
'car_post' : post.objects.filter(category__name = 'car')[:3]
I tried this code but i think it shows first 3 post in db
what can i do?
Solution
You can reverse the queryset with .reverse()
[Django-doc]:
post.objects.filter(category__name='car').reverse()[:3]
but very likely you can this more effective and descriptive if you can order, for example with a field like created_at
, then it is:
post.objects.filter(category__name='car').order_by('-created_at')[:3]
this is also better in the sense that a QuerySet
, unless ordered somehow, does not guarantee any ordering, so depending on the database, it can each time return objects in a different order.
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
topost
Post
.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.