Feb-18-2021, 03:52 PM
Hey there everybody! I am trying to return the number of threads and posts that belong to that specific forum. The structure is like this: Category -> Forum -> Thread.
Look at the picture attached
I want to query the database for all threads and posts that belong to that Forum and get the count of each.
This is my current code:
Models.py
Look at the picture attached
I want to query the database for all threads and posts that belong to that Forum and get the count of each.
This is my current code:
Models.py
class Forum(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='forums') def __str__(self): return self.name class Thread(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) thread_forum = models.ForeignKey(Forum, on_delete=models.CASCADE) def __str__(self): return self.name class Post(models.Model): post_body = models.TextField(blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post_date = models.DateTimeField(auto_now_add=True) post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE) def __str__(self): return str(self.id) + ' | ' + str(self.author)Views.py
class HomeView(ListView): context_object_name = 'name' template_name = 'index.html' queryset = Category.objects.all() def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) return contextindex.html
{% for forum in category.forums.all %} <div class="container-fluid forum-threads clearfix"> <div class="forum_threads_count"> 100 </div> <div class="forum_threads_threads"> <span>Threads</span> </div> </div> <div class="container-fluid forum-posts clearfix"> <div class="forum_posts_count">100</div> <div class="form_posts_text"> <span>Posts</span> </div> </div> <div class="container-fluid forum-latest-posts clearfix"> {% endfor %}I wish I could do this inside index.html but I can't:
{{ Thread.filter(forum=forum).count()) }}Got any ideas for a simple way to incorporate this? Thank you!