2014-07-08 33 views
0

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

以下是我的模型: -

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运行的数据库,但在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. 

这是怎么发生的?我知道重量是一个char字段,并且我添加了一个char字段,我认为这在postgres中是不允许的,但是如何改变我的查询以使其起作用?还有,为什么它工作在MySQL,而不是在Postgres的

回答

2

I know that weight is a char field and I'm adding a char field, which I suppose is not allowed in postgres, but how can alter my query so that it works ?

或者:

  • 使用合适的数据类型weight - 可能是float4float8double precision),但也许numeric如果你需要它;或

  • 转换为数值型聚集之前,让你运行SUM(CAST("data_shipmentweightmapping"."weight" AS float4))

Also , why it works in MySql and not in postgres

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

如果你在严格的ANSI模式下运行MySQL(你应该总是这样做),那么它会让你更容易理解奇怪的事情,或者不会。

+0

我该如何在Django ORM中做到这一点? – PythonEnthusiast

+0

@ user1162512理想情况下:将列类型更改为模型中的正确类型。如果你的意思是“我如何在Django ORM查询中键入一列”......不知道。我建议发布一个Django特定的问题,然后连接到这个问题的上下文。 –