在Django的一个简单的论坛应用中,在每个线程上,我想在同一页面上的几个用户呈现帖子(在用户帖子的用户面板上,就像所有传统论坛一样)。
以下是模型:
class Post(models.Model):
title = models.CharField(max_length=75, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
topic = models.ForeignKey(Topic)
body = models.TextField(max_length=10000)
class Topic(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=10000, null=True)
forum = models.ForeignKey(Forum)
created = models.DateTimeField()
creator = models.ForeignKey(User, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
closed = models.BooleanField(blank=True, default=False)
published = models.BooleanField(blank=True, default=False)
visits = models.IntegerField(default = 0)
weight = models.IntegerField(blank=True, default=0)
slug = models.CharField(max_length=100, blank=True)
def num_posts(self):
return self.post_set.count()
def num_replies(self):
return max(0, self.post_set.count() - 1)
def last_post(self):
if self.post_set.count():
return self.post_set.order_by("-created")[0]
def __unicode__(self):
return unicode(self.creator) + " - " + self.title
def save(self, *args, **kwargs):
super(Topic, self).save(*args, **kwargs)
我也有这个奇怪的模型:
class PostCount(models.Model):
user = models.OneToOneField(User)
posts = models.IntegerField(default=0)
@classmethod
def create(cls, user):
postcount = cls(user=user)
return postcount
以某种方式神奇地返回用户的主题数(不是帖子数),以便可以使用{{topic.creator.postcount.posts}}
在模板中访问它们。
以及呈现主题的视图:
def topic(request, topic_id):
"""Listing of posts in a topic."""
posts = Post.objects.filter(topic=topic_id).order_by("created")
posts = mk_paginator(request, posts, DJANGO_SIMPLE_FORUM_REPLIES_PER_PAGE)
topic = Topic.objects.get(pk=topic_id)
topic.visits += 1
topic.save()
forum = topic.forum
return render_to_response("myforum/topic.html", add_csrf(request, posts=posts, pk=topic_id,
topic=topic, forum= forum), context_instance=RequestContext(request))
所以我想知道用户在模板中如何最好地发布帖子数量?
答案 0 :(得分:1)
您是否不想使用内置计数,因为这可以解决您的问题。
views.py-应该获得所有用户,如果你想要一个选定的用户组本身就可以使用过滤器
context = {}
post_numbers = Post.objects.all().count()
context['post_numbers'] = post_numbers
模板
{{ post_numbers }}