在Django使用F()和timedelta进行查询 [英] Making queries using F() and timedelta at django
本文介绍了在Django使用F()和timedelta进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型:
class Process(models.Model):
title = models.Charfield(max_length=255)
date_up = models.DateTimeField(auto_now_add=True)
days_activation = models.PositiveSmallIntegerField(default=0)
现在,我需要根据其days_activation
的值来查询所有已过期的Process
对象.
Now I need to query for all Process
objects that have expired, according to their value of days_activation
.
我尝试过
from datetime import datetime, timedelta
Process.objects.filter(date_up__lte=datetime.now()-timedelta(days=F('days_activation')))
并收到以下错误消息:
TypeError:timedelta days组件的不受支持的类型:F
我当然可以用Python做到:
I can of course do it in Python:
filter (lambda x: x.date_up<=datetime.now() - timedelta(days=x.days_activation),
Process.objects.all ()),
但是我真的需要产生一个django.db.models.query.QuerySet
.
but I really need to produce a django.db.models.query.QuerySet
.
推荐答案
您必须扩展Aggregate.像下面这样:
You have to extend Aggregate. Do like below:
from django.db import models as DM
class BaseSQL(object):
function = 'DATE_SUB'
template = '%(function)s(NOW(), interval %(expressions)s day)'
class DurationAgr(BaseSQL, DM.Aggregate):
def __init__(self, expression, **extra):
super(DurationAgr, self).__init__(
expression,
output_field=DM.DateTimeField(),
**extra
)
Process.objects.filter(date_up__lte=DurationAgr('days_activation'))
希望它会为您工作. :)
Hopefully, It will work for you. :)
这篇关于在Django使用F()和timedelta进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文