2013-07-02 22 views
0

我正在爲網站創建簡單的通知系統。用戶的通知從數據庫中提取,如果尚未顯示,則會標記爲已顯示,然後顯示給用戶。那些未被看見的以粗體顯示。下面是我的一些代碼:停止SQLAlchemy更新已從數據庫中提取的行

query = request.db.query(Notification)\ 
     .filter(Notification.user == request.user) 
notifications = query.order_by(Notification.created_at.desc()).all() 

print [ notif.seen for notif in notifications ] # [ False, False, False... ] 
query.filter(Notification.seen == False).update({ 
    'seen': True 
    }) 
request.db.commit() 
print [ notif.seen for notif in notifications ] # [ True, True, True... ] 

你會從我的打印報表時執行update查詢,儘管已經被從數據庫中抽取與.all()注意到notifications被修改。

我不想要這種行爲。我需要看看什麼notifications,而不是它,以便大膽的領域,以前是不可見的。

通過文檔查看,我認爲設置synchronize_session參數爲False可能工作。

query.filter(Notification.seen == False).update({ 
    'seen': True 
    }, False) 

但不幸的是,它沒有。

我該如何解決這個問題?

回答

0

synchronize_session =假如你正在做的,但你也需要在查看通知之前不提交,或者在你的會話中打開expire_on_commit = False。對象通常在提交後第一次訪問時從數據庫刷新。

+0

是的,關掉了'expire_on_commit',它工作完美。 –

0

我認爲這不值得在這裏做任何棘手的事情,比如破壞會話中的同步或刪除對象。在這種情況下,最好先保存未預先看到的通知列表,然後在應用程序中稍後使用。

new_notifications = [notif for notif in notifications if not notif.seen] 

# do the update stuff 
pass 

# later on 
for notif in notifications: 
    if notif in new_notifications: 
     # This one is new, do some stuff 
     pass 
    else: 
     # We already saw this notification, do some other stuff 
     pass 

如果你需要更好的性能商店的ID在字典中並覈對:

new_notifications = dict([(notif.id, None) for notif in notifications if not notif.seen]) 

if notif.id in new_notifications: 
    pass 

最後一個解決辦法是在一個更設置臨時屬性在這樣的通知(也許用一個類的方法或東西)正式辦法:

for notif in notifications: 
    notif.fresh = not notif.seen 

然後你的代碼依賴於新的設定,並使用它

相關問題