Django:在 ListView 中显示评分计数

Django: Display Count of Ratings in ListView

我刚开始学习 django,我正在尝试在 ListView 中显示具有评级数量的产品。但是我未能生成预期的输出。

models.py

class Product(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(max_length=255, default=None)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    
    
class ProductRating(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_rating')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    stars = models.SmallIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])

views.py

class ProductListView(LoginRequiredMixin, ListView):
    model = Product

    def get_queryset(self):
        return Product.objects.annotate(avg_rating=Avg('product_rating__stars')).order_by('-avg_rating')

    def get_context_data(self, **kwargs):
        data = super(ProductListView, self).get_context_data(**kwargs)
        data['product_rating_count'] = Product.objects.annotate(Count('product_rating'))
        return data

模板

{{ product.name }} {{ product.avg_rating }} {{ product_rating_count }}

这会按预期显示名称和平均评分,但会在每个产品旁边放置一个包含所有产品的查询集,如下所示:

<QuerySet [<Product: testp1>, <Product: testp2>, <Product: testp3>, <Product: testp4>]>

在您的模板中,您可以这样做。

{% for product in products %}

{{ product.name }} {{ product.avg_rating }} 

Rating count: {{ product.product_rating.all.count }}

{% endfor %}