在Django的一个简单的论坛应用程序中,我希望在每个线程上由多个用户在同一页面上呈现帖子(就像你在VB和其他经典论坛上看到的那样)。
以下是模型:
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))
我试过这个
posts = Post.objects.filter(topic=topic_id).order_by("created").annotate(creator_post_count=Count(creator__post_set))
但它不起作用。
所以我想知道如何最好地计算模板中用户的帖子数量?
答案 0 :(得分:2)
.left { float: left; width: 48%; margin-right: 2%; }
.right { float: left; width: 50%; }
或直接在模板中打印posts = Post.objects.filter(topic=topic_id).order_by('created').annotate(creator_post_count=Count('creator__post_set_id', distinct=True))
?