Django嵌套查询循环

时间:2019-02-08 22:53:18

标签: mysql django

我想在“评论”页面上显示评论列表和每个评论的评分。

我当前的逻辑是,如果不是最好的方法,请纠正我,以获取所有评论(变量reviews),然后将该查询放入另一个名为ratings的查询中,以获取所请求值的平均值。

这是一些信息。 models.py

class Review(models.Model):
     author = models.ForeignKey(User, on_delete=models.CASCADE)
     title = models.CharField(max_length=100)
     content = models.TextField()
     value1 = models.CharField(max_length=1)
     value2 = models.CharField(max_length=1)
     value3 = models.CharField(max_length=1)
     value4 = models.CharField(max_length=1)

view.py

def reviews(request):
    ratings=[]
    reviews = Employee.objects.all()

    for review in reviews:
        ratings = Employee.objects.filter(id=review.id).aggregate(rate=Avg(F('culture')+F('location')+F('salary_satis')+F('work_env')+F('communication')+F('opportunity')+F('leadership_satis')+F('fair_treatment'))/8)

    context = {
        'reviews': reviews,
        'ratings': ratings
    }
    return render(request, 'reviews/reviews.html', context)

reviews.html

{% extends "reviews/layout.html" %}
{% block content %}
    {% for review in reviews %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ review.author.profile.image.url }}">
          <div class="media-body">
            <div class="article-metadata">
              <h4 class="mr-2">{{ review.company }} {{ ratings.rate }}</h4>
              <small class="text-muted">{{ review.date_posted|date:"F d, Y" }}</small>
            </div>
            <h5><a class="article-title" href="{% url 'review-detail' review.id %}">{{ review.title }}</a></h5>
            <p class="article-content">{{ review.content }}</p>
          </div>
        </article>
    {% endfor %}
{% endblock content %}

到目前为止,每条评论的公司名称旁边都有相同的评分结果。它没有显示与评论​​有关的每个评分。我在做什么错了?

0 个答案:

没有答案