Django-模型:查询/过滤器中的for循环

时间:2019-02-03 19:49:47

标签: django django-queryset

我有一个评论列表,每个评论都有一个平均评分。我的问题是尝试将每个评论ID添加到查询结果的过滤器中。为此,我认为过滤器中的for循环是最好的。

我发现以前的帖子也有类似的情况,但是相同的结果似乎对我不起作用。

加载评论页面时,我收到TypeError:'function' object is not iterable

这是我的带有查询的view.py文件。

def reviews(request):
    context = {
        'reviews': Employee.objects.all(),

        'rating': Employee.objects.filter(id__in=[review.id for review in reviews]).aggregate(rate=Avg(F('value1')+F('value2')+F('value3').....+F('valueN'))/N)
    }
    return render(request, 'reviews/reviews.html', context)

Reviews.html模板。

{% extends "reviews/layout.html" %}
{% block content %}
    {% for review in reviews %}
      {% for rating in ratings %}
        <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 }} {{rating}}</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 %}
    {% endfor %}
{% endblock content %}

任何建议都值得赞赏。

编辑:这是我的Employee表模型。

class Employee(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    company = models.CharField(max_length=100)
    recommend = models.BooleanField(default=False)
    salary = models.CharField(max_length=100)
    salary_satis = models.CharField(max_length=100)
    culture = models.CharField(max_length=100)
    location = models.CharField(max_length=100)
    work_env = models.CharField(max_length=100)
    communication = models.CharField(max_length=100)
    opportunity = models.CharField(max_length=100) # Opportunity happiness
    leadership_satis = models.CharField(max_length=100)
    fair_treatment = models.CharField(max_length=100)
    advice = models.TextField() # Advice for management
    date_posted = models.DateTimeField(default=timezone.now)

    author = models.ForeignKey(User, on_delete=models.CASCADE)
    class Meta:
        ordering = ['-date_posted']

    def __str__(self):
        return f'{self.title, self.content, self.company, self.recommend, self.salary, self.salary_satis, self.culture, self.location, self.work_env, self.communication, self.opportunity, self.leadership_satis, self.fair_treatment, self.advice, self.date_posted, self.author}'

    def get_absolute_url(self):
        # Returns user to reviews page after their review has been submitted.
        return reverse('reviews')

1 个答案:

答案 0 :(得分:0)

您在字典中的reviews是指reviews视图功能(此​​处均为黑体字):

def reviews(request):
    context = {
        'reviews': Employee.objects.all(),
        'rating': Employee.objects.filter(
            id__in=[review.id for review in reviews]
        ).aggregate(
            rate=Avg(F('value1')+F('value2')+F('value3').....+F('valueN'))/N
        )
    }
    return render(request, 'reviews/reviews.html', context)

实际上,您无法遍历此函数,因为它没有附加任何__iter__方法,但是即使有,这也不是您想要执行的操作。

我认为解决此问题的最优雅方法是简单地定义一个reviews变量:

def reviews(request):
    reviews = Employee.objects.all()
    context = {
        'reviews': reviews,
        'rating': Employee.objects.filter(
            id__in=[review.id for review in reviews]
        ).aggregate(
            rate=Avg(F('value1')+F('value2')+F('value3').....+F('valueN'))/N
        )
    }
    return render(request, 'reviews/reviews.html', context)

因此,reviews现在是您可以访问的局部变量,并且由于queryseet是可迭代的,因此我们可以对此进行迭代。

话虽这么说,在这里使用id__in有点奇怪,因为reviews具有 all Employee s。