【问题标题】:How do i fix No function matches the given name and argument types. You might need to add explicit type casts如何修复没有函数与给定名称和参数类型匹配。您可能需要添加显式类型转换
【发布时间】:2019-10-04 15:06:27
【问题描述】:
already_transferred = Transfer.objects.all().filter(transferred_by=request.user, account_id=id).aggregate(total=Coalesce(Sum('amount'), 0))

并且服务器给出了这个错误

function sum(text) does not exist
LINE 1: SELECT COALESCE(SUM("API_insidetransfer"."amount"), 0) AS "a...
                        ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

这是我的模型

class Transfer(models.Model):
    transferred_by = models.CharField(max_length=120)
    account_id = models.CharField(max_length=120)
    amount = models.CharField(max_length=120, default=0)
    created_on = models.DateTimeField(auto_now=True)

我该如何解决这个问题?

【问题讨论】:

  • amountCharField?
  • 是的,我有其他模型,其中数量是 CharField 并且可以工作
  • 当然行得通,只要您获取或存储数据,那肯定行得通。但在这里,您的目标是总结金额。你不能总结字符串。

标签: python django postgresql


【解决方案1】:

问题是您的amountCharField。您不能对字符字段求和。例如,'foo''bar' 的总和是多少。

因此,您应该在模型级别解决问题:将amount 设为DecimalField(或IntegerField)。例如:

class Transfer(models.Model):
    transferred_by = models.CharField(max_length=120)
    account_id = models.CharField(max_length=120)
    amount = modelsDecimalField(max_digits=12, decimal_places=2, default=0)
    created_on = models.DateTimeField(auto_now=True)

【讨论】:

  • 谢谢,让我试试,会告诉你的!
猜你喜欢
  • 2021-02-05
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多