python - Django - 如何按注释值过滤
问题描述
考虑以下模型。我想根据最新的时间戳过滤对象,可能是created_at
或updated_at
。出于某种原因,该filter
函数无法识别带注释的字段,我很难找到合适的代码示例来完成这个简单的事情。
错误消息是“无法将关键字 'timestamp' 解析为字段。”。
根据较新的日期,您将如何在 7 天内检索示例对象。
from datetime import timedelta
from django.db import models
from django.db.models.functions import Greatest
from django.utils import timezone
class Example(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
@property
def recently_updated(self):
return Event.objects
.annotate(timestamp=Greatest('created_at', 'updated_at'))
.filter(timestamp__gte=timezone.now() - timedelta(days=7))
.order_by('-timestamp')
姜戈 1.11
解决方案
只需设置updated_at = models.DateTimeField(auto_now=True, null=True)
,这样第一次插入记录时,update_at 和 created_at 将是相同的,因此,您可以在 updated_at 上运行查询:
Event.objects.filter(updated_at__gte=timezone.now() - timedelta(days=7)).order_by('-timestamp')
推荐阅读
- pandas - 如何从日期时间序列中构建带有月份的列?
- javascript - 如何在不打开窗口的情况下打开电子应用程序
- java - 如何防止 DialogFragment 调整大小
- facebook-graph-api - 从服务器调用 Facebook API /{user-id}/picture?access_token=xxxxxx 的最佳方式?
- c++ - std::copy 指向易失数据的指针
- node.js - OpenShift“无法设置源密码”
- c - 如何编写 C 函数将整数翻译成英文短语?
- javascript - 需要解决 XMLHttpRequest 预检问题的方法
- univocity - Univocity 解析是否支持 java 8 日期时间类型转换(LocalDateTime)?
- mysql - 查找一列的重复项,但仅在另一列具有相同值时才返回结果