获取类别的最新帖子

时间:2013-07-08 15:18:54

标签: python django

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

1 个答案:

答案 0 :(得分: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 %}