如何使用“早于 n 天”的布尔值注释 Django 查询集?

问题描述 投票:0回答:1

给出模型的玩具示例:

class Article(models.Model):
    title = models.CharField(max_length=64)
    published = models.DateTimeField()

你如何获得一个查询集,这样你就可以判断这篇文章是否发表于 2 年前?

我在想这样的事情,但没有成功:

Article.objects.all().annotate(
    is_relevant=ExpressionWrapper(
        timezone.now() - F("start") > timedelta(days=365 * 2),
        output_field=BooleanField(),
    )
)

基本上,我希望能够遍历文章列表并访问模板中的

article.is_relevant
来决定我如何呈现它。

django django-orm
1个回答
0
投票

以相反的方式使用它:

from django.db.models import ExpressionWrapper Q
from django.db.models.functions import Now

Article.objects.annotate(
    is_relevant=ExpressionWrapper(
        Q(published__gte=Now() - timedelta(days=2 * 365)),
        output_field=BooleanField(),
    )
)

我们因此检查它是否在两年前之后发布。

© www.soinside.com 2019 - 2024. All rights reserved.