Django:查询不同类别的最新帖子 [英] Django: query latest posts from different categories

查看:200
本文介绍了Django:查询不同类别的最新帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Post(models.Model):
    title = ...
    category = models.ForeignKey(Category)
    date = .......

class Category(models.Model):
    title = ....

在主页上,我想显示最新日期的5个帖子,但所有帖子必须来自不同的类别。例如有50个类别。可以吗?

On the main page i want to display 5 posts with latest dates, but all posts must be from different categories. There is 50 categoriese, for example. Is it possible?

推荐答案

from django.db.models import Max

categories = Category.objects.annotate(most_recent=Max(post__date)).order_by('-most_recent')[:5]

posts = list()
for category in categories:
  posts.append(category.post_set.latest())

注释最新帖子的日期类别为 most_recent ,然后您可以订购以获取最新的5个类别。

That annotates the categories with the date of the most recent post as the value of most_recent, which you can then order by to get the 5 most recent categories.

然后,只需循环遍历类别,并为每个类别拉出最新的帖子。完成。

Then, just loop through the categories and pull out the latest post for each. Done.

这篇关于Django:查询不同类别的最新帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆