如何在django中调用双嵌套反向外键关系



我正在做论坛项目。目前,我需要以某种方式获取每个类别的最新帖子。

我的模型结构如下(伪代码(:

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)

最新更新