0

ウェブサイト用の簡単な通知システムを作成しています。ユーザーの通知はデータベースから取得され、まだ表示されていない場合は表示済みとしてマークされ、ユーザーに表示されます。見られなかったものは太字で表示されます。これが私のコードの一部です:

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

でデータベースから既にプルされているにもかかわらずnotifications、クエリが実行されると変更される私の print ステートメントから気付くでしょう。update.all()

私はこの動作をしたくありません。以前は見られなかったフィールドを太字にするために、それ何であるかではなく、何notifications があったかを確認する必要があります。

ドキュメントを見て、synchronize_session引数をに設定するとFalseうまくいくかもしれないと思いました。

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

しかし、残念ながらそうではありませんでした。

どうすればこれを修正できますか?

4

2 に答える 2

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

最後の解決策の 1 つは、次のように通知に一時的なプロパティを設定することです (おそらく、クラス メソッドなどを使用したより正式な方法で):

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

次に、コードは設定されているフレッシュに依存し、それを使用します

于 2013-07-02T23:26:44.417 に答える