我刚开始学习django,我正试图在ListView中显示一个具有评级数量的产品。但我未能产生预期的产出。
型号.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)])
视图.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,如下所示:
<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 %}