考虑以下模型。我想根据最新时间戳过滤对象,该时间戳可能是 created_at
或 updated_at
。由于某种原因,filter
函数无法识别带注释的字段,我很难找到合适的代码示例来完成这个简单的事情。
错误消息是“无法将关键字“时间戳”解析到字段中。”。
您将如何根据较新的日期在 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')
Django 1.11
最佳答案
只需设置updated_at = models.DateTimeField(auto_now=True, null=True)
,这样第一次插入记录时updated_at和created_at将相同,因此,您可以运行update_at 上的查询:
Event.objects.filter(updated_at__gte=timezone.now() - timedelta(days=7)).order_by('-timestamp')
关于python - Django - 如何按注释值过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643130/