Python /:‘;的操作数类型不受支持;地图&x2019;和';int’;
为什么会出现这个错误?7号线出了什么问题 不确定为什么要使用numpy来完成此操作。您可以自己轻松地计算平均值,但为什么不让数据库通过其聚合功能来计算呢Python /:‘;的操作数类型不受支持;地图&x2019;和';int’;,python,django,Python,Django,为什么会出现这个错误?7号线出了什么问题 不确定为什么要使用numpy来完成此操作。您可以自己轻松地计算平均值,但为什么不让数据库通过其聚合功能来计算呢 ##models.py from django.db import models from django.contrib.auth.models import User import numpy as np class Wine(models.Model): name=models.CharFi
##models.py
from django.db import models
from django.contrib.auth.models import User
import numpy as np
class Wine(models.Model):
name=models.CharField(max_length=200)
def average_rating(self):
all_ratings = map(lambda x: x.rating, self.review_set.all())
return np.mean(all_ratings)
def __unicode__(self):
return self.name
这将对您有用:-
from django.db.models import Avg
...
def average_rating(self):
return self.review_set.aggregate(Avg('rating'))['rating__avg']
这应该对你有用:改变
from django.db import models
from django.contrib.auth.models import User
import numpy as np
class Wine(models.Model):
name=models.CharField(max_length=200)
def average_rating(self):
all_ratings = list(map(lambda x: x.rating, self.review_set.all()))
return np.mean(all_ratings)
def __unicode__(self):
return self.name
到
它对我有用
感谢在中,map()
返回一个iterable,而在中,它返回一个列表。python iterable和整数之间的任何数学运算(如mean)都会引发类似的错误。该行:
return np.mean(list(all_ratings))
在Python3中抛出上述错误,因为
all\u ratings
是由函数map()
返回的一个iterable。您可能正在使用Python 3。因此,在进行任何数学运算之前,您需要将all_ratings
转换为list,例如,np.mean(list(all_ratings))
如果您遇到错误,您可以发布完整的回溯吗?我假设numpy不喜欢map对象,请尝试通过list(map(…)
)将其制作成一个列表。谢谢@syntonym它工作了感谢您的解决方案。我制作了列表而不是map,它工作了。
return np.mean(list(all_ratings))
return np.mean(all_ratings)