我正在尝试在我的论坛应用程序中获取每个类别的最新帖子。我一直在尝试Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1])
我希望能够在我的模板中使用这些值: postID
、、title
和。user
pub_date
模型.py:
class Category(models.Model):
catID = models.CharField(max_length=20, primary_key=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=200)
class Post(models.Model):
postID = models.CharField(max_length=10, primary_key=True)
catID = models.ForeignKey(Category)
user = models.CharField(max_length=100)
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField(auto_now=True)
视图.py:
def index(request):
cats = Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1])
context = {'forum_cats': cats}
return render(request, 'forums/index.html', context)