我试图获得模型中字段的平均值,但我一直收到这个错误:
Exception Type: ProgrammingError
Exception Value:
function avg(character varying) does not exist
LINE 1: SELECT AVG("home_course"."course_difficulty") AS "course_dif...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
这是我的模型领域,我得到了平均值:
class Difficulty(models.TextChoices):
EASY = '1', 'Easy'
MEDIUM = '2', 'Medium'
HARD = '3', 'Hard'
FAILED = '4', 'Failed'
course_difficulty = models.CharField(
max_length=2,
choices=Difficulty.choices,
default=Difficulty.MEDIUM
)
我正在使用这个查询:
avg = Course.objects.filter(course_code=self.course_code,course_university=self.course_university).aggregate(Avg('course_difficulty'))
(course_code
和course_university
都是CharFields(
现在,经过搜索,我意识到这可能是因为course_difficuly
是一个CharField,我如何在不丢失文本选择的情况下将其转换为整数?我可以简单地将其更改为IntegerField吗?
您可以使用Cast-django数据库函数
class Cast(表达式,输出字段(
强制表达式的结果类型为output_field中的结果类型。
以下行中的某些内容
avg = Course.objects.filter(
course_code=self.course_code,
course_university=self.course_university
).annotate(
course_difficulty_int=Cast('course_difficulty', IntegerField()
).aggregate(
Avg('course_difficulty_int')
)