Django如何在forloop

时间:2019-05-05 22:07:58

标签: html django

我正在尝试在循环内的html文件中使用数组

观看次数

def noticia(request, noticia_id):
   noticia = get_object_or_404(Noticia, pk=noticia_id)
   user_like = False
   likes = []
   dislikes = []
   x = 0
   for comentario in noticia.comentario_set.all().order_by('-pub_data'):
       likes.append(0)
       dislikes.append(0)
   for comentario in noticia.comentario_set.all():
       for like in comentario.like_set.all():
           if like.like:
               likes[x] += 1
           elif like.dislike:
               dislikes[x] += 1
           if like.user == request.user:
               user_like = True
   return render(request, 'Bola/Noticia.html', {'noticia': noticia, 'user_like': user_like, 'likes': likes,
                                                'dislikes': dislikes})

HTML

{% for comentario in noticia.comentario_set.all|dictsortreversed:"pub_data"%}
  {% for like in comentario.like_set.all %}
    <p>{{ likes.forloopcounter0 }} {{ dislikes.forloopcounter0 }}</p>

有什么主意要怎么做吗?

1 个答案:

答案 0 :(得分:0)

使用Conditional Aggregation可能是一种更好的方法。

要使用该功能,首先让我们使用related_name更新Comentario和Like之间的ForeignKey关系:

class Like(models.Model):
    comment = models.ForeignKey(Comentario, related_name='likes', on_delete=models.CASCADE)

现在在查询集中使用该相关名称:

from django.db.models import Count, Case, When, IntegerField

...

comments = noticia.comentario_set.all().annotate(
    like_count=Count(Case(
        When(likes__like=True, then=1),
        output_field=IntegerField(),
    )).annotate(dislike_count=Count(Case(
        When(likes__like=False, then=1),
        output_field=IntegerField(),
    ))
)

return render(request, 'Bola/Noticia.html', {'comments': comments})

然后在模板中使用它:

{% for comentario in comments %}
   {{ comentario.like_count }}
   {{ comentario.dislike_count }}
{% endfor %}