我有 db.model 像:
class UserProfile(db.Model):
__tablename__ = 'UserProfile'
nickname = db.Column(db.String(40), primary_key=True)
wm = db.Column(db.Boolean)
def __init__(self,name):
self.nickname = name
self.wm = 1
def __repr__(self):
return '<UserProfile {nickname}>'.format(username=self.nickname)
在用户登录期间 - 我正在尝试从数据库中检索记录 并将其值存储在 session 变量中 -
userprofile = UserProfile(form.username.data)
userprofile = UserProfile.query.filter_by(nickname=form.username.data).first()
session['wm']=userprofile.wm
但它失败并显示如下消息:
session['wm']=userprofile.wm
AttributeError: 'NoneType' object has no attribute 'wm'
Mysql 数据库:
mysql> desc UserProfile;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| nickname | varchar(40) | NO | PRI | NULL | |
| wm | tinyint(1) | YES | | NULL | |
它也有记录。
感谢您的帮助。
最佳答案
您实际上需要先添加您的新 UserProfile
对象到数据库:
userprofile = UserProfile(form.username.data)
db.session.add(userprofile)
参见 Flask-SQLAlchemy documentation on insertion :
Before you add the object to the session, SQLAlchemy basically does not plan on adding it to the transaction. That is good because you can still discard the changes. For example think about creating the post at a page but you only want to pass the post to the template for preview rendering instead of storing it in the database.
The
add()
function call then adds the object.
关于python - flask : retrieve data from db and store it session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15599519/