给出模型的玩具示例:
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
来决定我如何呈现它。
以相反的方式使用它:
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(),
)
)
我们因此检查它是否在两年前之后发布。