gpt4 book ai didi

python - '编程错误 : function avg(character varying) does not exist' - Django project

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:54 25 4
gpt4 key购买 nike

我最近将一个 Django 项目部署到 Heroku。在浏览器中测试功能时,我在尝试呈现特定模板时遇到了一个新错误:

ProgrammingError at /accelerators/6/
function avg(character varying) does not exist
LINE 1: SELECT AVG("reviews_review"."mentorship") AS "avg_mentorship...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

此问题从未在开发服务器中出现,但我想我知道问题出在哪里。我在我的 Accelerator 模型中使用 Avg 来确定字段的十进制值 (avg_mentorship),方法是确定输入(指导)到另一个模型(审查)的平均数。

我的指导字段是一个字符字段,其中的选项是作为字符串的数字。我已经包含了以下任一模型的相关代码:

class Accelerator(models.Model):
avg_mentorship = models.DecimalField(decimal_places=2, max_digits=3)

@property
def avg_mentorship(self):
quantity = Review.objects.filter(subject=self)
if len(quantity) > 0:
mentorship_result = Review.objects.filter(subject=self).aggregate(avg_mentorship=Avg('mentorship'))['avg_mentorship']
else:
mentorship_result = 0
return mentorship_result

class Review(models.Model):
RATINGS = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
)
mentorship = models.CharField(choices=RATINGS, blank=False, max_length=1, default='1')

def save(self, *args, **kwargs):
self.mentorship = int(self.mentorship)
super(Review, self).save(*args, **kwargs)

这似乎是一个非常简单的修复,所以我在审查模型中添加了一些将指导转换为 int 的代码。但是,这并没有解决问题,所以我想知道是否有任何理由导致我修改后的代码不起作用,以及我在解释错误消息时是否绝对正确(这不是我的强项)。非常感谢任何输入。谢谢。

最佳答案

您应该将指导设为IntegerField [Django-doc] (或 FloatFieldIntegerField),例如:

class Review(models.Model):
RATINGS = (
(<b>1</b>, '1'),
(<b>2</b>, '2'),
(<b>3</b>, '3'),
(<b>4</b>, '4'),
(<b>5</b>, '5'),
)
mentorship = models.<b>IntegerField</b>(choices=RATINGS, default=1)

您无法计算 CharField 的平均值。 'foo''bar' 的平均值是多少?因此,您需要将数据存储到数字 字段中。

迁移它可能需要一些工作。如果您不需要保留现有数据,我建议您只删除构建 Review 模型的迁移文件,然后重新使用此模型和表。

请注意,您可以通过以下方式提高计算聚合的效率:

class Accelerator(models.Model):

@property
def avg_mentorship(self):
return self.review_set.aggregate(
avg_mentorship=Avg('mentorship')
)['avg_mentorship'] or 0

关于python - '编程错误 : function avg(character varying) does not exist' - Django project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57613970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com