0

I'm creating a simple notification system for a website. The user's notifications are pulled from the database, marked as seen if they haven't been already, and then displayed to the user. The ones that were unseen are displayed in bold. Here's some of my code:

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... ]

You'll notice from my print statements that notifications is modified when the update query is executed, despite already being pulled from the database with .all().

I don't want this behavior. I need to see what notifications was, not what it is, in order to bold the fields that have previously been unseen.

Looking through the docs, I thought setting the synchronize_session argument to False might work.

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

But unfortunately, it did not.

How might I fix this?

4

2 回答 2

0

synchronize_session=False 就像你正在做的那样,但你也需要在查看通知之前不提交,或者在你的会话中打开 expire_on_commit=False 。该对象通常在提交后首次访问时从数据库中刷新。

于 2013-07-03T20:32:04.380 回答
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

然后你的代码依赖于新设置并使用它

于 2013-07-02T23:26:44.417 回答