如何删除django中的会话变量?

ezd*_*kie 6 python django

我的会话变量是'cart':

cart = {'8': ['a'], ['b'], '9': ['c'], ['d']}
Run Code Online (Sandbox Code Playgroud)

如果我想删除我的所有购物车变量,我只需在Python中执行此操作:

del request.session['cart']
Run Code Online (Sandbox Code Playgroud)

但我只是想删除键'8',所以我尝试这个但它不起作用:

del request.session['cart']['8']
Run Code Online (Sandbox Code Playgroud)

但是,如果我打印request.session ['cart'] ['8']并获得a,b

agc*_*nti 7

django会话对象只能在修改后保存.但是因为您正在修改会话中的对象,所以会话对象不知道它被修改,因此无法保存.

要让会话对象知道其修改后的用法:

request.session.modified = True
Run Code Online (Sandbox Code Playgroud)

来自django文档:

https://docs.djangoproject.com/en/dev/topics/http/sessions/

保存会话时默认情况下,Django仅在会话被修改时保存到会话数据库 - 即,如果已分配或删除任何字典值:

# Session is modified. 
request.session['foo'] = 'bar'

# Session is modified. 
del request.session['foo']

# Session is modified. 
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session. request.session['foo']['bar'] = 'baz' 
Run Code Online (Sandbox Code Playgroud)

在上面示例的最后一种情况中,我们可以通过在会话对象上设置modified属性来明确告诉会话对象它已被修改:

  request.session.modified = True
Run Code Online (Sandbox Code Playgroud)

要更改此默认行为,请将SESSION_SAVE_EVERY_REQUEST设置为True.设置为True时,Django会在每个请求中将会话保存到数据库.

请注意,会话cookie仅在创建或修改会话时发送.如果SESSION_SAVE_EVERY_REQUEST为True,则会在每次请求时发送会话cookie.

同样,每次发送会话cookie时,会话cookie的到期部分都会更新.

如果响应的状态代码为500,则不会保存会话.