0

我正在尝试在我的论坛应用程序中获取每个类别的最新帖子。我一直在尝试Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1]) 我希望能够在我的模板中使用这些值: postID、、title和。userpub_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)
4

1 回答 1

1

一种方法是

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):
        post = self.post_set.order_by('-pub_date')
        if post:
            return post[0]
        return None

在模板中,

{% for cat in forum_cats %}
    {% if cat.latest_post %}
        {{cat.latest_post.title}}
    {% endif %}
{% endfor %}
于 2013-07-08T15:24:34.873 回答