首页 > 解决方案 > Django - 如何按注释值过滤

问题描述

考虑以下模型。我想根据最新的时间戳过滤对象,可能是created_atupdated_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

标签: pythondjango

解决方案


只需设置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')

推荐阅读