在Django中测试空/空字符串 [英] testing for empty/null string in django

查看:308
本文介绍了在Django中测试空/空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下内容的charfield:

  myString = models.CharField(max_length = 50,null = True,blank = True)

在我的许多对象中,当通过django管理界面。在MySQL中,该列为VARCHAR(50),默认值为NULL。



无论我尝试在自己的views.py中执行什么测试以检测空值,似乎总是在评估判断条目是否为空为否:

  myString为None 
myString ==
len(myString)== 0

如何区分该字段的空白值和非空白值?



谢谢



编辑:



实际视图如下,仅当此字段不为空时,我才想执行块。

 如果myObject.myString:
#做某事

该块始终执行,并且我尝试了上述所有测试示例一个空白字段。 :确实有效。

解决方案

如果您的 d None k-

 如果d:
#做某事
其他:
#做其他


I have a charfield with the following:

myString = models.CharField(max_length=50,null=True,blank=True)

In many of my objects, this particular string is often left blank, when created through the django admin interface. In MySQL, the column is VARCHAR(50) with default=NULL.

Whatever test I try to do in my views.py to detect blank values, always seems to evaluate to false whether the entry is blank or not:

myString is None
myString==""
len(myString)==0

How can I discriminate between blank and non-blank values for this field?

Thanks

EDIT:

Actual view is the following, I want to execute a block only if this field is not blank.

if myObject.myString:
     #do something

the block always executes, and I have tried all the above examples of testing for a blank field.

EDIT 2:

Scratch that, if myObject.myString: does indeed work.

解决方案

if your d is either None or "" then simply check -

if d: 
    #do something
else:
    #do something else

这篇关于在Django中测试空/空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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