0
我有兩個模型,Post和Vote。用戶可以upvote和downvote帖子。Django得到每個職位的票數總和
models.py:
class Post(models.Model):
poster = models.ForeignKey('auth.User')
question = models.ForeignKey('self', null=True, blank=True)
post_title = models.CharField(max_length=300)
post_content = models.TextField(null=True, blank=True)
is_published = models.BooleanField(default=True)
is_locked = models.BooleanField(default=False)
is_question = models.BooleanField(default=True)
is_deleted = models.BooleanField(default=False)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
date_modified = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.post_title
class Vote(models.Model):
user = models.ForeignKey('auth.User')
post = models.ForeignKey('Post')
vote_type = models.SmallIntegerField()#-1, 0, 1
date_voted = models.DateTimeField(
default=timezone.now)
def __str__(self):
return self.user
我用下面的代碼在我看來,在帖子返回模板:
views.py:
def index(request):
posts = Post.objects.filter(created_date__lte=timezone.now(
), is_question=1, is_published=1).order_by('-created_date')
#removed the paging stuff here for simplification
return render(request, 'homepage/index.html', {'posts': posts})
這只是返回崗位,但我也希望每個帖子的vote_type列的總和是該帖子的總投票數。
當前我使用每個帖子的模板標籤來檢查每個帖子的投票。
我的index.html的示例代碼:
{% for post in posts %}
{{ post|total_votes|default:"0" }}
{% endfor %}
有什麼辦法來查詢在views.py一切,然後在模板我可以檢查這樣的:{{post.total_votes}}?