Reputation: 443
I'm trying to get the latest post for each of the category in my forum app. I've been trying things like Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1])
I want to be able to do use the values: postID
, title
, user
and pub_date
in my template.
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)
Upvotes: 0
Views: 66
Reputation: 99660
One way is
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
and in the template,
{% for cat in forum_cats %}
{% if cat.latest_post %}
{{cat.latest_post.title}}
{% endif %}
{% endfor %}
Upvotes: 1