【问题标题】:Django Postgres Aggregate FunctionsDjango Postgres 聚合函数
【发布时间】:2014-07-08 04:15:21
【问题描述】:

我想在模型中的列上使用聚合函数。

以下是我的模型:-

class ShipmentWeightMapping(models.Model):
    weight = models.CharField(max_length = 255)
    status = models.CharField(max_length = 255)
    time = models.DateTimeField( auto_now_add = True)
    shipment_id = models.ForeignKey('Shipment', related_name = 'weights')

这是我的聚合查询:-

shipment_weight_obj = ShipmentWeightMapping.objects.filter(shipment_id__in = shipment_id_list).aggregate(Avg('weight'),Max('weight'),Min('weight'),Sum('weight'))
total_weight = shipment_weight_obj['weight__sum']
max_weight = shipment_weight_obj['weight__max']
min_weight = shipment_weight_obj['weight__min']
avg_weight = shipment_weight_obj['weight__avg']

上面的代码以 MySQL 作为 DB 运行,但与 postgres 一起使用时返回错误:-

LINE 1: SELECT SUM("data_shipmentweightmapping"."weight") AS "weight...
[Tue Jul 08 04:05:38 2014] [error]                ^
[Tue Jul 08 04:05:38 2014] [error] HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

这是怎么回事?我知道 weight 是一个 char 字段,我正在添加一个 char 字段,我认为它在 postgres 中是不允许的,但是如何更改我的查询以使其正常工作?另外,为什么它在 MySql 中而不是在 postgres 中有效

【问题讨论】:

    标签: mysql django postgresql aggregate-functions


    【解决方案1】:

    我知道 weight 是一个 char 字段,我正在添加一个 char 字段,我认为 postgres 中不允许这样做,但是如何更改我的查询以使其正常工作?

    要么:

    • weight 使用合适的数据类型 - 可能是 float4float8 (double precision),但如果需要,也可能是 numeric;或

    • 在聚合之前转换为数值类型,因此您可以运行 SUM( CAST("data_shipmentweightmapping"."weight" AS float4))

    另外,为什么它在 MySql 中有效,而不是在 postgres 中

    MySQL 可以让你做 PostgreSQL 不能做的各种疯狂的事情。就像将一堆文本字段添加在一起并将它们隐式转换为数字一样。插入零作为日期。比较空值是否相等。

    如果您在 STRICT ANSI 模式下运行 MySQL(您应该始终这样做),那么它可以让您做或不做的奇怪事情会更加明智。

    【讨论】:

    • 如何在 Django ORM 中做到这一点?
    • @user1162512 理想情况下:将列类型更改为模型中的正确类型。如果您的意思是“我如何在 Django ORM 查询中对列进行类型转换”……不知道。我建议发布一个关于 Django 的特定问题并链接回这个问题以获取上下文。
    猜你喜欢
    • 1970-01-01
    • 2011-04-11
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多