我正在尝试获取给定类别中所有产品的每个产品的平均评分(在评论模型中找到)。我很难做到这一点。相关的 urlconf、视图和模板如下:
url(r'^category/(?P<category_id>\d+)/$', 'view_product_category'),
class Productbackup(models.Model):
website = models.CharField('Product name', max_length = 200)
website_url = models.URLField('Product URL')
category = models.ForeignKey(Categories)
def __unicode__(self):
return self.website
class ProductbackupForm(ModelForm):
class Meta:
model = Productbackup
def get_avg_rating(self):
reviews = Reviewbackup.objects.filter(product=self)
count = len(reviews)
sum = 0
for rvw in reviews:
sum += rvw.rating
return (sum/count)
class Reviewbackup(models.Model):
review = models.CharField('Review', max_length = 2000)
rating = models.IntegerField(max_length=200)
product = models.ForeignKey(Product)
def __unicode__(self):
return self.review
class Categories(models.Model):
category = models.CharField('Category_second', max_length = 200)
def __unicode__(self):
return unicode(self.category)
def view_product_category(request, category_id):
allproduct = Productbackup.objects.filter(category_id=category_id)
#get average for each product within a category
return render_to_response('reserve/templates/view_category.html', {'allproduct':allproduct},
context_instance=RequestContext(request))
{% for product in allproduct %}
<a href = "/products/{{ product.id}}/reviews"> {{ product.website }}</a>: <a href = "{{ product.website_url }}"> Direct link</a><br>
#average rating for that product
{{ product.get_avg_rating }}
{% endfor %}