如何检查ImageField是否为空 [英] How to check ImageField is empty

查看:216
本文介绍了如何检查ImageField是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有一个ImageField,当我保存它时,我想检查一下是否没有。



在django shell中我打电话我的对象的ImageField,它给出:

 >>> p.avatar 
< ImageFieldFile:None>
>>> p.avatar是无
False

我发现ImageField的名字是那么有什么更好的办法吗?

解决方案


我发现ImageField的名字是
u任何更好的方法来做
它?


其实,这个类似于这个类如何评估 bool(),所以更好的方法是通过调用来测试其 bool(),如果p.avatar



ImageFieldFile 子类文件 ,其定义为:

  def __nonzero __(self):
return bool(self.name)

所以更好的方法是:

 code>如果不是p.avatar:
打印我不存在

bool(p.avatar)是False


I have an ImageField in my model and when I'm saving it I want to check that if it's None or not.

In django shell I'm calling my object's ImageField and it gives :

>>> p.avatar
<ImageFieldFile: None>
>>> p.avatar is None
False

I found that the ImageField's name is u'', so is there any better way to do it ?

解决方案

I found that the ImageField's name is u'', so is there any better way to do it ?

Actually, it looks like that's exactly how this class evaluates bool(), so the better way is to just test its bool() by calling if p.avatar

ImageFieldFile subclasses File, which defines:

def __nonzero__(self):
    return bool(self.name)

So the better way is indeed:

if not p.avatar:
   print "I don't exist"

bool(p.avatar) is False

这篇关于如何检查ImageField是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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