发布数据时如何检查名称/值对是否存在? [英] How to check if a name/value pair exists when posting data?

查看:47
本文介绍了发布数据时如何检查名称/值对是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到执行所需操作的正确语法。如果不存在名称/值对,我想做些事情。这是我认为的代码:

I'm not able to find the proper syntax for doing what I want to do. I want to do something if a name/value pair is not present. Here is the code in my view:

if (!request.POST['number']):
    # do something

完成上述工作的正确方法是什么?尝试此操作时遇到语法错误。

What is the proper way to accomplish something like the above? I am getting a syntax error when I try this.

推荐答案

@Thomas为您提供了通用方法,但是有一个快捷方式

@Thomas gave you the generic way, but there is a shortcut for the particular case of getting a default value when a key does not exist.

number = request.POST.get('number', 0)

这等效于:

if 'number' not in request.POST:
    number = 0
else:
    number = request.POST['number']

这篇关于发布数据时如何检查名称/值对是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆