django-2.0 - 我们可以使用 Django "F" 表达式修改 django 查询集中的值吗?查询优化
问题描述
now = datetime.utcnow().replace(tzinfo=utc)
.annotate(
age=F(int((now - 'ended_at').total_seconds() / (60 * 60)))
我想在 Django 查询中添加上面的逻辑。基本上我想计算“年龄”,这是需要执行 ORM 操作的原因。如果我使用 for 循环执行此操作,则数据量大且需要时间。
解决方案
首先定义 aFunc
以提取自 UNIX 纪元以来的秒数。
from django.db.models import Func, IntegerField
class UnixTime (Func):
"""
Extract the number of seconds since January 1, 1970.
"""
arity = 1
output_field = IntegerField()
# for PostgreSQL
def as_sql(self, compiler, connection, **extra_context):
return super().as_sql(
compiler, connection,
template="EXTRACT(EPOCH FROM %(expressions)s)",
**extra_context)
def as_mysql(self, compiler, connection, **extra_context):
return super().as_sql(
compiler, connection,
template="UNIX_TIMESTAMP(%(expressions)s)",
**extra_context)
def as_sqlite(self, compiler, connection, **extra_context):
return super().as_sql(
compiler, connection,
template="CAST(strftime('%%%%s', %(expressions)s) AS INTEGER)",
**extra_context)
然后进行这样的查询:
from django.db.models import F
from django.db.models.functions import Now
YourObject.objects.annotate(
age=(UnixTime(Now()) - UnixTime(F('ended_at'))) / 3600
)
推荐阅读
- powershell - 需要有关 powershell 中 where-object 的帮助
- css - 带有 angularjs 的 style="-webkit-mask-image: url()" 中的 HTTP 404
- google-sheets - 如何将此 Google 工作表的内容动态导入新工作表?
- datetime - 如何计算周末、节假日等休息日交易的数量?
- asp.net - ASP.Net 核心 web api 中的数据库查询过滤
- javascript - 从 javascript 到 C# 的函数解码器
- c# - 无法将 Json 对象反序列化为类型
- java - 我可以将一段代码作为参数添加到方法中吗?
- javascript - debounceTime 每次发送请求
- gitlab-ce - 无法将 GitLab CE 从 13.4.3 更新到 13.5.4