我有2个课程,产品和评级。
if(this.on){
我试图获得两个数字之间的平均评分,我试过了:
class Product(models.Model):
type = models.CharField(max_length=20)
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to = 'img/', default = 'img/no-img.png')
slug = models.SlugField(unique=True, default = (randint(0,1000000)))
def get_avg_rating(self):
avg_rating = self.rate_set.all().aggregate(Avg('rating'))
if avg_rating['rating__avg']:
return round(avg_rating['rating__avg'],1)
else:
return 0
class Rate(models.Model):
user = models.ForeignKey(User)
product= models.ForeignKey(Product, blank=True, null=True)
rating = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0))
以上没有从数据库中获取任何结果。评级列表的值是Product.objects.filter(name__icontains=search, rate__rating__lte=rating[0], rate__rating__gte=rating[1])
,我在数据库中有一个平均评级为2的对象。不返回该对象,我没有错误。是否可以在数据库级别查询上述内容,还是应该在python中进行查询?
答案 0 :(得分:2)
尝试按结果注释平均评分和过滤查询集:
Product.objects.filter(name__icontains=search).annotate(avg_rating=Avg('rate__rating')).filter(avg_rating__lte=rating[0], avg_rating__gte=rating[1])