所以我从sqlite切换到postgresql来制作我的django评论网站 - 但由于psql是强类型的,我的代码有错误
LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
所以我想我可以通过将我的 CharFields 更改为 IntegerFields 来更改类型,以将类型更改为 int... 像这样
move_in_condition = models.CharField(max_length=5,choices=RATING_CHOICES, blank=False, default='5')
treatment = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5")
response_speed = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5")
maintenance_quality = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5")
自
move_in_condition = models.IntegerField(choices=RATING_CHOICES, blank=False, default=5)
treatment = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5)
response_speed = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5)
maintenance_quality = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5)
有选择:
class Review(models.Model):
RATING_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
但后来我在某处读到sql不直接支持将字符串列更改为int列......所以我仍然遇到同样的错误。我尝试删除我的数据库再次创建新的数据库,但在迁移后仍然收到相同的错误。
我相信这是触发错误的位
def get_avg(self):
return self.reviews.annotate(
overall_rating = Sum(
F('move_in_condition') +
F('treatment') +
F('response_speed') +
F('maintenance_quality')
)/4).aggregate(
Avg('overall_rating'),
Avg('move_in_condition'),
Avg('treatment'),
Avg('response_speed'),
Avg('maintenance_quality')
)
但是,是的,我只是想显示公司等的几个平均评论,并且在尝试了几天后似乎无法弄清楚。 提前感谢!
您有一个强制转换问题,因此首先您需要回答,¿您真正需要的数据类型是什么?如果选择 CharField,则可以直接在查询中强制转换字段,如下所示:
Avg(int('your_field'))
正如曼努埃尔所说,刚刚添加了int((!
def get_avg(self):
return self.reviews.annotate(
overall_rating = Sum(int(
F('move_in_condition') +
F('treatment') +
F('response_speed') +
F('maintenance_quality')
))/4).aggregate(
Avg('overall_rating'),
Avg('move_in_condition'),
Avg('treatment'),
Avg('response_speed'),
Avg('maintenance_quality')
)