【问题标题】:Django session delete json objectDjango会话删除json对象
【发布时间】:2017-06-10 15:04:59
【问题描述】:

如何从具有 'pk':50 的会话中删除对象并将其存储在所有页面中。当我修改请求会话时,我将 SESSION_SAVE_EVERY_REQUEST=True 添加到 Settings.py 和 request.session.modified = True 到上面一行,但没有任何效果。

Json 看起来像

[
{
    "pk": 50, 
    "model": "notifications.notification", 
    "fields": {
        "recipient": 81, 
        "verb": "commented", 
        "emailed": false, 
        "action_object_object_id": "", 
        "level": "info", 
        "deleted": false, 
        "timestamp": "2017-01-25T11:18:53.197Z", 
        "target_content_type": null, 
        "actor_object_id": "1", 
        "action_object_content_type": null, 
        "target_object_id": "790", 
        "actor_content_type": 3, 
        "unread": true, 
        "data": "\"\"", 
        "public": true, 
        "description": "commented on your request"
    }
}, 
{
    "pk": 38, 
    "model": "notifications.notification", 
    "fields": {
        "recipient": 81, 
        "verb": "commented", 
        "emailed": false, 
        "action_object_object_id": "", 
        "level": "info", 
        "deleted": false, 
        "timestamp": "2017-01-24T12:23:08Z", 
        "target_content_type": null, 
        "actor_object_id": "1", 
        "action_object_content_type": null, 
        "target_object_id": "790", 
        "actor_content_type": 3, 
        "unread": true, 
        "data": "\"\"", 
        "public": true, 
        "description": "commented on your request"
    }
}
]

代码

def setNotifRead(request, notif_id):
    notifObject = Notification.objects.filter(pk=notif_id)
    notifObject.update(unread=0)
    notifications = request.session['notifications']
    request.session.modified = True
    del notifications[notif_id] # Something should be done here
    return

【问题讨论】:

  • 我看不出向我们展示 JSON 数据的意义。您应该显示视图的代码。
  • 代码已添加,我知道我必须找到 pk=50 的对象的索引,然后我可以轻松删除此会话。

标签: json django session


【解决方案1】:

您需要遍历数据并过滤没有相关 ID 的项目。

notifications = [item for item in request.session['notifications'] if item['id'] != notif_id
request.session['notifications'] = notifications

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2023-02-14
    • 2017-06-26
    • 1970-01-01
    相关资源
    最近更新 更多