2013-07-08 79 views
0

我試圖在我的論壇應用程序中獲取每個類別的最新帖子。我一直在嘗試諸如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

一種方法是

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 %} 
+0

哦,哇。太棒了!謝謝:) – Jeremy

+0

或者使用[這裏]描述的簡單'get_latest_by'模型元選項(https://docs.djangoproject.com/en/dev/ref/models/options/#get-latest-by) –