TypeError: type CombinedExpression doesn't define __round__ method

TypeError: type CombinedExpression doesn't define __round__ method

我在 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 doesn't define round method" 错误?

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)