我正在使用以下模型来存储数据。
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
timestamp=db.Column(DateTime(timezone=True), nullable=False)
def __init__(self, username, timestamp=None):
self.username = username
if timestamp is None:
timestamp =datetime.datetime.now()
self.timestamp = timestamp
def __repr__(self):
return '<User %r>' % self.username
现在,我的问题是:使用
user = User.query.filter_by(username='admin').first()
我了解数据将被提取并转换为User
对象?
总而言之,我要完成的工作是,在使用上述查询获取数据时,将自动对数据进行操作。
也就是说,在我的情况下,时间戳是已知的。我将使用pytz.localize()来做到这一点。
我试过了 :
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
timestamp=db.Column(DateTime(timezone=True), nullable=False)
def __init__(self, username, timestamp=None):
self.username = username
if timestamp is None:
timestamp =datetime.datetime.now()
timestamp = pytz.utc.localize(timestamp)
self.timestamp = timestamp
def __repr__(self):
return '<User %r>' % self.username
我认为是,当对象初始化时,
if(timestamp is none)
new entry
initialize timestamp
make timezone aware #even if fetched from db
self.timestamp=timestamp`
但是,它不起作用。__init__
查询数据时不调用。该怎么办?
我在sqlalchemy文档中发现,从一行重新创建对象时,它不使用__init __()。
参见:http : //docs.sqlalchemy.org/en/latest/orm/constructors.html
从数据库行重新创建对象时,SQLAlchemy ORM不调用__init__。ORM的过程有点类似于Python标准库的pickle模块,它调用了底层__new__方法,然后直接在实例上安静地还原属性,而不是调用__init__。
如果需要在数据库加载的实例准备好使用之前对其进行一些设置,则可以使用@reconstructor装饰器将方法标记为__init__的ORM副本。每次加载或重建一个实例时,SQLAlchemy都将在不带参数的情况下调用此方法。这对于重新创建通常在__init__中分配的瞬态属性很有用:
from sqlalchemy import orm
class MyMappedClass(object):
def __init__(self, data):
self.data = data
# we need stuff on all instances, but not in the database.
self.stuff = []
@orm.reconstructor
def init_on_load(self):
self.stuff = []
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句