gpt4 book ai didi

python - Flask-SQLAlchemy : Manipulate attribute of a data upon fetching

转载 作者:行者123 更新时间:2023-12-01 03:27:27 27 4
gpt4 key购买 nike

我使用以下模型来存储数据。

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

The SQLAlchemy ORM does not call __init__ when recreating objects from database rows. The ORM’s process is somewhat akin to the Python standard library’s pickle module, invoking the low level __new__ method and then quietly restoring attributes directly on the instance rather than calling __init__.

If you need to do some setup on database-loaded instances before they’re ready to use, you can use the @reconstructor decorator to tag a method as the ORM counterpart to __init__. SQLAlchemy will call this method with no arguments every time it loads or reconstructs one of your instances. This is useful for recreating transient properties that are normally assigned in your __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 = []

关于python - Flask-SQLAlchemy : Manipulate attribute of a data upon fetching,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297997/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com