【问题标题】:Django: Display Count of Ratings in ListViewDjango:在 ListView 中显示评分计数
【发布时间】:2021-09-02 19:25:12
【问题描述】:

我刚开始学习 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>]>

【问题讨论】:

    标签: python django django-queryset annotate


    【解决方案1】:

    在您的模板中,您可以执行此操作。

    {% for product in products %}
    
    {{ product.name }} {{ product.avg_rating }} 
    
    Rating count: {{ product.product_rating.all.count }}
    
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 2018-09-24
      • 2020-08-16
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多