0
我試圖在我的論壇應用程序中獲取每個類別的最新帖子。我一直在嘗試諸如Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1])
我希望能夠在我的模板中使用值:postID
,title
,user
和pub_date
。獲取類別的最新日誌
models.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)
views.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)
哦,哇。太棒了!謝謝:) – Jeremy
或者使用[這裏]描述的簡單'get_latest_by'模型元選項(https://docs.djangoproject.com/en/dev/ref/models/options/#get-latest-by) –