Django得到每个帖子的总票数

时间:2017-02-17 16:39:05

标签: python django

我有两个模型,Post和Vote。用户可以投票和投票。

models.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})

我在视图中使用以下代码将帖子返回给模板:

views.py:

    {% for post in posts %}
       {{ post|total_votes|default:"0" }} 
    {% endfor %}

这只是返回帖子,但我也想要每个帖子的vote_type列的总和,这是该帖子的总投票数。

目前,我为每个帖子使用模板标签来检查每个帖子的投票。

我的index.html示例代码:

Dim KeyStage As String
Dim NCY As Integer

NCY = Me.NationalCurriculumYear.Value

If NCY < 1 Then
Me.KeyStage = "Early Years"
ElseIf NCY > 0 And NCY < 3 Then
Me.KeyStage = "KS1"
ElseIf NCY > 2 And NCY < 7 Then
Me.KeyStage = "KS2"
ElseIf NCY > 6 And NCY < 10 Then
Me.KeyStage = "KS3"
ElseIf NCY > 9 And NCY < 12 Then
Me.KeyStage = "KS4"
Else: Me.KeyStage = "Left School"
End If

有没有办法查询views.py中的所有内容,然后在模板中我可以像这样检查:{{post.total_votes}}?

2 个答案:

答案 0 :(得分:2)

是的,你可以使用annnotate。通常,它看起来像

Authentication = succeeded
for = active directory
user: = bobtheperson
account: = bobtheperson@com.com
reason: = N/A
Access cont(upn): = bob

from django.db.models import Sum posts = Post.objects.filter(...).annotate(total_votes=Sum('vote__vote_type')) 中的每个post对象将具有posts属性。

答案 1 :(得分:1)

使用汇总https://docs.djangoproject.com/en/2.2/topics/db/aggregation/

另一种解决方法是在Post模型中定义一种方法,以计算特定Post对象的vote_type数量,如下所示

# models.py
from django.db.models import Sum

class Post(models.Model):
   ......
       def total_votes(self):
        return Post.objects.filter(pk=self.id).aggregate(Sum('vote__vote_type'))

并为了获得temaplte中的total_vote_type

# post.html
{% for post in posts %} 
# Assuming in views you are passing the posts As posts = Post.objects.all()
    {{ post.total_votes.vote__vote_type__sum }}
{% endfor %}
相关问题