我正在做论坛项目。目前,我需要以某种方式获取每个类别的最新帖子。
我的模型结构如下(伪代码(:
class Category(models.Model):
...
class Topic(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
...
class Post(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
...
我需要在Category
模型的函数中获取最新的Post
对象,这样我就可以在模板中调用后者。
使用单个反向外键调用,我会做如下操作:category: Category = self.topic_set.all()
,但我需要为Post
更深一层。
有没有比[topic.post_set.first() for topic in self.topic_set.all()]
这样的列表理解更聪明的方法呢??
您可以使用Subquery
表达式[Django-doc]在两个查询中执行此操作,该表达式将根据Topic
:获得最新的Post
from django.db.models import OuterRef, Subquery
post_ids = Topic.objects.filter(
category=my_category
).values_list(
Subquery(
Post.objects.filter(
topic_id=OuterRef('pk')
).order_by('-created').values('pk')[:1]
),
flat=True
)
posts = Post.objects.filter(pk__in=post_ids)