1👍
✅
Just add slice after filter so for example:
post_by_category = Post.objects.filter(published=True).order_by('-category')[:5]
About inserting them into dictionary.
If you only got some categories, you could filter them each and slice 5 of them and insert it to your dictionary
news = Post.objects.filter(category="news")[:5]
travel = Post.objects.filter(category="travel")[:5]
categories = {
'news': news,
'travel': travel
}
Or you could filter all your posts, and then loop them and check their categories and insert them to respective lists (This code is highly inefficient btw, as you could stop after adding 5 data on all lists)
news_post_list = list()
travel_post_list = list()
for post in posts:
if post.category == "news":
news_post_list.append(post)
elif post.category == "travel":
travel_post_list.append(post)
categories = {
'news': news_post_list[:5],
'travel': travel_post_list[:5]
}
You got the idea
Source:stackexchange.com