一种解决方法是使用 Django 的 annotate() 方法。annotate() 方法允许你在查询结果中添加额外的字段。在你的情况下,你可以使用 annotate() 方法来添加一个名为 latestpost 的字段,该字段包含每个类别的最新帖子。
以下是在 models.py 中修改Category模型的示例:
from django.db.models import Max
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)
def latest_post(self):
return Post.objects.filter(catID=self.catID).order_by('-pub_date').first()
在上面的代码中,我们定义了一个名为 latest_post() 的方法。该方法返回与该类别关联的最新帖子。
然后,你可以在视图中使用 annotate() 方法来添加 latestpost 字段。以下是在 views.py 中修改 index() 视图的示例:
from django.db.models import Max
def index(request):
cats = Category.objects.annotate(latestpost=Max('post__pub_date')).order_by('catID')
context = {'forum_cats': cats}
return render(request, 'forums/index.html', context)
在上面的代码中,我们使用 annotate() 方法添加了一个名为 latestpost 的字段。该字段包含每个类别的最新帖子的发表日期。
最后,你可以在模板中使用 latestpost 字段来显示每个类别的最新帖子。以下是在 index.html 中的示例:
{% for cat in forum_cats %}
{% if cat.latest_post %}
{{ cat.latest_post.title }}
{% endif %}
{% endfor %}
现在,你就可以在模板中显示每个类别的最新帖子了。
代码例子:
# 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)
def latest_post(self):
return Post.objects.filter(catID=self.catID).order_by('-pub_date').first()
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
from django.db.models import Max
def index(request):
cats = Category.objects.annotate(latestpost=Max('post__pub_date')).order_by('catID')
context = {'forum_cats': cats}
return render(request, 'forums/index.html', context)
# index.html
{% for cat in forum_cats %}
{% if cat.latest_post %}
{{ cat.latest_post.title }}
{% endif %}
{% endfor %}