我有两个模型,如:
class Category(models.Model):
title = models.CharField(max_length=100)
expires_in_days = models.PositiveIntegerField(default=20)
class Item(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100)
description = models.TextField()
category = models.ForeignKey(Category)
我需要确定哪些项目应该设置过期:
items_to_cancel = Item.objects.annotate(expires_date=F('created') + F('category__expires_in_days'))\
.filter(expires_date__lte=timezone.now().date())
运行此查询会引发异常:
FieldError: Expression contains mixed types. You must set output_field.
更新
将查询更新为
后items_to_cancel = Item.objects.annotate(expires_date=ExpressionWrapper(F('created') + F('category__expires_in_days'), output_field=DateField()))\
.filter(expires_date__lte=timezone.now().date())
我遇到了这个例外:
ProgrammingError: operator does not exist: timestamp with time zone + integer.
所以现在我无法弄清楚如何从时间戳中获取日期。
答案 0 :(得分:1)
感谢Daniel Roseman对ExpressionWrapper的评论。但是我必须再做一次更新才能使它工作,我必须将TruncDate
函数应用于时间戳:
from django.db.models.functions import TruncDate
items_to_cancel = Item.objects.annotate(
expires_date=ExpressionWrapper(
TruncDate('created') + F('category__expires_in_days'),
output_field=DateField()
)
).filter(expires_date__lte=timezone.now().date())