python - 如何创建包含不同类型的查询集表达式

标签 python django postgresql django-models

我有两个模型:

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.

所以现在我不知道如何从时间戳中获取日期。

最佳答案

感谢 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())

关于python - 如何创建包含不同类型的查询集表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47671551/

相关文章:

database - 如果 postgres 中的语句抛出错误

mysql - 是否仍在使用 XA/JTA 事务?

django - 重复键值在保存 ModelForm 时违反了唯一约束

python - Django 中的元素计数

python - 在嵌套字典列表中添加平均值的键

python - 如何在 Django 中以编程方式呈现和缓存 View ?

django - 在 IIS 上部署 Django 应用程序的推荐方法是什么?

python - 多字符串变量声明python

python - 为什么我的代码不打印整个列表?

python - Django ORM - 将此自连接查询转换为 ORM