简体   繁体   English

django Model.objects.raw返回SUM字段为Decimal

[英]django Model.objects.raw returns SUM field as Decimal

I have a django model defined as follows: 我有一个定义如下的django模型:

class Foo(models.Model):
    bar = models.IntegerField(null=True)
    baz = models.ForeignKey(Baz)

class Baz(models.Model):
    bat = models.IntegerField(null=True)

I perform a Foo.objects.raw() aggregation query on it as follows: 我对它执行Foo.objects.raw()聚合查询,如下所示:

sql = """
      SELECT -1 AS id,
      SUM( foo.bar ) AS bar
      FROM myapp_foo
      LEFT JOIN myapp_baz ON foo.baz_id = baz.id
      GROUP BY myapp_baz.id;
      """

aggregate_foo = Foo.objects.raw(sql)

Which all works fine, but when I access aggregate_foo.bar it returns a Decimal instead of an int! 一切正常,但是当我访问aggregate_foo.bar时,它将返回一个小数而不是一个整数! Of course I could cast bar into an int after the fact but I'd rather do this the right way. 当然,事实发生后我可以将int转换为int,但是我宁愿以正确的方式进行操作。

Has anybody else run into this undocumented "feature" of the django raw() function? 还有其他人遇到过django raw()函数的这个未记录的“功能”吗? Is there a proper way to write the sql so that it will return the SUM( ) field as an int? 是否有编写sql的正确方法,以便它将int返回SUM()字段? I understand that I don't NEED to perform a raw query in the example above, but let's just assume for the sake of this question that I can't use Foo.objects.aggregate( ) 我了解我不需要在上面的示例中执行原始查询,但是为了这个问题,我们仅假设我不能使用Foo.objects.aggregate()

Dunno if it's crucial to this question but my datastore is MySQL 5.5 Dunno(对于这个问题至关重要),但我的数据存储区是MySQL 5.5

It is a feature of MySQL, and not django. 它是MySQL的功能,而不是django。 Hence not documented in django. 因此没有在django中记录。

From the documentation 文档中

For numeric arguments, the variance and standard deviation functions return a DOUBLE value. 对于数字参数,方差和标准偏差函数返回DOUBLE值。 The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE). SUM()和AVG()函数为精确值参数(整数或DECIMAL)返回DECIMAL值,为近似值参数(FLOAT或DOUBLE)返回DOUBLE值。 (Before MySQL 5.0.3, SUM() and AVG() return DOUBLE for all numeric arguments.) (在MySQL 5.0.3之前,SUM()和AVG()对于所有数字参数都返回DOUBLE。)

Hence the result. 因此,结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM