How To Split Post View On The Same Page In Django
I have no idea if this question make much sense or not but i am so confused about it. I have a post list view and it is rendering some of the post here. My question is how can I sp
Solution 1:
You have posts assigned to categories. Each post could be assigned only to one category (since you have FK from Post
to Category
). And you want to display all categories and 10 latest posts under each one.
I see several ways of how to solve that. The easiest one is to extend Category
model with property, containing the queryset to retrieve related posts in the way you want them for front page.
classPost(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='posts')
date_posted = models.DateTimeField(default=timezone.now)
classCategory(models.Model):
title = models.CharField(max_length=255)
@propertydefposts_for_frontpage(self):
return self.posts.order_by('-date_posted')[:10]
classFrontpageView(ListView):
model = Category
template_name = 'frontpage.html'
context_object_name = 'categories'defget_queryset(self):
# select some categories for frontpage# all by defaultreturn Category.objects.all()
and then in template
{% for category in categories %}
<h1>{{ category.title }}</h1><hr />
{% for post in category.posts_for_frontpage %}
<h4>{{ post.title }}</h4>
{% endfor %}
<br /><br />
{% endfor %}
You could also play with select_related
to reduce number of queries and with annotate
to get all related posts.
Post a Comment for "How To Split Post View On The Same Page In Django"