【问题标题】:TypeError: type CombinedExpression doesn't define __round__ methodTypeError:类型 CombinedExpression 没有定义 __round__ 方法
【发布时间】:2019-01-27 02:28:56
【问题描述】:

我在 PyCharm 中使用 ipython (Python 3.7) 控制台。我正在尝试运行一个 Django ORM 查询,我想在其中进行一些日期数学运算,专门计算秒数并将其与另一个字段进行比较。我试过了

Article.objects.filter(article_stat__elapsed_time_in_seconds=(round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300)

但我收到以下错误

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-18-607b95229a28>", line 1, in <module>
    Article.objects.filter(article_stat__elapsed_time_in_seconds=(round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300)
TypeError: type CombinedExpression doesn't define __round__ method

这是有问题的模型...

class Article(models.Model):
    ...
    created_on = models.DateTimeField(default=datetime.now)

如何克服“TypeError: type CombinedExpression does not define round method”错误?

【问题讨论】:

  • 您使用的是什么数据库?您将 Python 代码(四舍五入)与 Django 拼写 SQL 过滤器的方式混合在一起。 datetime.now(timezone.utc) - F("created_on") 表达式转换为 SQL WHERE 过滤器,必须在在该级别进行舍入。

标签: python django python-3.x orm rounding


【解决方案1】:

datetime.now(timezone.utc) - F("created_on") 是一个组合表达式;你不能将它传递给 Python round() 函数,这里没有要舍入的具体数字,无论如何你都希望在数据库级别进行舍入。

如果我们假设您正在连接到实现 ROUND 函数的数据库,那么您可以使用 Func() expression 在 Django 过滤器中表达:

from django.db.models import F, Func

time_filter = (
    Func(
        datetime.now(timezone.utc) - F("created_on"),
        function='ROUND'
    ) / 300) * 300
Article.objects.filter(article_stat__elapsed_time_in_seconds=time_filter)

【讨论】:

  • 谢谢。我正在使用 PostGres 9.5。我收到“提示:没有函数与给定名称和参数类型匹配。您可能需要添加显式类型转换。”在实现你的逻辑之后,但我认为这更多是我尝试使用 Postgres 的 ROUND 和日期减法的问题。我要去研究一下,然后我会回来接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2018-04-02
  • 2020-12-24
  • 2021-09-02
  • 2022-11-21
  • 2021-08-02
相关资源
最近更新 更多