我有一个处方模型。
from datetime import timedelta
from sqlalchemy.ext.hybrid import hybrid_property
class Prescription(db.Model):
""" docstring """
ID = db.column(db.Integer, primary_key=True)
date = db.Column(db.DateTime)
duration = db.Column(db.SmallInteger)
@hybrid_property
def expiration_date(self):
# return self.date + timedelta(days=self.duration)
return self.date + timedelta(days=7)
@classmethod
def actual(cls ):
""" docstring """
today = datetime.today()
return cls.query.filter(Prescription.expiration_date>=today)
我只想在我的实际方法中以及指定时获得实际处方
@hybrid_property
def expiration_date(self):
return self.date + timedelta(days=7)
一切都像魅力。
但是每个处方都有不同的持续时间,并且在我指定时
@hybrid_property
def expiration_date(self):
return self.date + timedelta(days=self.duration)
我有一个错误
TypeError: unsupported type for timedelta days component: InstrumentedAttribute
我试图像这样做点小技巧
@property
def days(self):
return int(self.duration)
但是没有运气。 谁能说出解决方法,或者为工期字段创建一些惰性对象,或者通过另一种方式获取实际处方,并根据计算出的expiration_date进行过滤?
答案 0 :(得分:1)
您可能正在尝试计算DATEDIFF: Calculate DATEDIFF in POSTGRES using SQLAlchemy
在这里,is_expired
将生成一个SQL查询部分,该部分将计算开始日期和utcnow()
之间的天数差异,并将结果与self.duration
这在PostgreSQL中有效,但我尚未在其他RDBMS上进行测试。
from datetime import datetime
import sqlalchemy as sa
class Prescription:
ID = db.column(db.Integer, primary_key=True)
date = db.Column(db.DateTime)
duration = db.Column(db.SmallInteger)
@hybrid_property
def is_expired(self):
days_since_published = sa.func.trunc((
sa.extract('epoch', datetime.utcnow()) -
sa.extract('epoch', self.date)
) / 3600 / 24)
return days_since_published >= self.duration
@classmethod
def active(cls):
return cls.query.filter(is_expired=False)
答案 1 :(得分:0)
在带有import io
class MyStream(io.BytesIO):
def __init__(self, val1, val2, val3):
print('MyStream.__init__')
def test():
testOle = MyStream('val1', 'val2', 'val3')
test()
注解的@classmethod
方法中,您尝试访问引发错误的非静态属性(expiration_date)。
据我对您的代码在做什么的理解,我对代码进行了如下更改:
actual()
输出:
我可以向您建议的一件事是,由于该模型不需要到期时间。 这样您就可以更改
from datetime import datetime,timedelta
from sqlalchemy.ext.hybrid import hybrid_property
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'
class Prescription(db.Model):
""" docstring """
def mydefault(context):
return context.get_current_parameters()['date'] + timedelta(days=context.get_current_parameters()['duration'])
ID = db.Column(db.Integer,primary_key= True)
date = db.Column(db.Date)
duration = db.Column(db.SmallInteger)
expiration_date = db.Column(db.Date,default = mydefault)
@classmethod
def actual(cls ):
""" docstring """
today = datetime.today().date()
return cls.query.filter(Prescription.expiration_date>=today).all()
def __repr__(self):
return "Id:{} , date:{}, duration:{}, expiration_date:{}".format(self.ID,self.date,self.duration,self.expiration_date)
db.create_all()
q=Prescription(ID=1,date=datetime(2019,5,26).date(),duration = 1) #Expired
r=Prescription(ID=2,date=datetime(2019,5,20).date(),duration = 3) #Expired
s=Prescription(ID=3,date=datetime(2019,5,27).date(),duration = 5) #Not Expired
t = Prescription(ID=4,date=datetime.now().date(),duration = 1) #Not Expired
db.session.add(q)
db.session.add(r)
db.session.add(s)
db.session.add(t)
db.session.commit()
list_obj = Prescription.query.all()
print("All Objects in DB:-")
for l in list_obj:
print(l)
print()
print("Valid Prescription:")
print(Prescription.actual())
到
date = db.Column(db.DateTime)
它将简化您的任务:)