2013-03-24 57 views
1

我有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) 

和用戶登錄時 - 我試圖從數據庫 retrive的記錄,它的價值保存在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 |  | 

它也有記錄。

感謝您的任何幫助。

回答

4

你需要真正添加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.

+0

但是如果我加上「 db.session.add(userprofile)下一次用戶登錄失敗,並顯示消息,如「sqlalchemy.exc.IntegrityError:(IntegrityError)(1062,」Duplicate entry「 – 2013-03-24 14:30:26

+3

然後查詢用戶對象* first *,只創建一個新的一個如果它不在那裏。 – 2013-03-24 14:32:36

0

添加你需要提交,以查看更改後

userprofile = UserProfile(form.username.data) 
db.session.add(userprofile) 
db.session.commit() 
相關問題