【问题标题】:No function matches the given name and argument types. You might need to add explicit type casts. Django Postgresql没有函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。 Django Postgresql
【发布时间】:2020-08-26 01:44:47
【问题描述】:

我正在尝试获取模型中某个字段的平均值,但我不断收到此错误:

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_codecourse_university 都是 CharFields)

现在搜索后我意识到这可能是因为course_difficuly 是一个字符字段,我怎样才能将它转换为整数而不丢失我的文本选择?我可以简单地将其更改为 IntegerField 吗?

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    可以使用Castdjango数据库函数

    class Cast(表达式, output_field)

    强制表达式的结果类型为 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')
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多