检查会话密钥是否设置
我正在尝试在 Django 中创建一个相对简单的购物车。我将购物车存储在 request.session['cart']
中。因此,当向其中添加任何内容时,我需要访问此会话中的数据。但是,如果会话尚未设置,我将无法在不收到错误的情况下访问它。有没有什么方法可以检查会话是否已设置,以便在会话不存在时也可以设置它?
I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']
. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there any way to check if a session is set, so that it can be set if it doesn't exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设您想检查会话中是否设置了key,而不是检查会话是否设置了(不知道后者意味着什么)。如果是这样:
您可以这样做:
在您的情况下:
编辑:将代码片段更改为使用
key not in
而不是not key in
。谢谢@katrielalex。I assume that you want to check if a key is set in session, not if a session is set (don't know what the latter means). If so:
You can do:
In your case:
EDIT: changed the code snippet to use
key not in
rather thannot key in
. Thanks @katrielalex.您可以在会话字典上使用
get
方法,如果键不存在,它不会抛出错误,但不返回任何值作为默认值或您的自定义默认值:You can use the
get
-method on the session dictionary, it will not throw an error if the key doesn't exist, but return none as a default value or your custom default value: