Python Django-文件字段检查是否无
我有一个带有可选文件字段的模型Python Django-文件字段检查是否无,python,django,django-models,Python,Django,Django Models,我有一个带有可选文件字段的模型 class MyModel(models.Model): name = models.CharField(max_length=50) sound = models.FileField(upload_to='audio/', blank=True) 让我们来计算一个值 >>> test = MyModel(name='machin') >>> test.save() 为什么我会这样 >>> te
class MyModel(models.Model):
name = models.CharField(max_length=50)
sound = models.FileField(upload_to='audio/', blank=True)
让我们来计算一个值
>>> test = MyModel(name='machin')
>>> test.save()
为什么我会这样
>>> test.sound
<FieldFile: None>
>>> test.sound is None
False
>test.sound
>>>测试声音是零
假的
如何检查是否存在文件集
if test.sound.name:
print "I have a sound file"
else:
print "no sound"
另外,FieldFile
的布尔值在没有文件时将为False:bool(test.sound)==False
当test.sound.name
为False时。根据不同问题的这一点,您可以尝试以下方法:
class MyModel(models.Model):
name = models.CharField(max_length=50)
sound = models.FileField(upload_to='audio/', blank=True)
def __nonzero__(self):
return bool(self.sound)
哪个布尔值?你的意思是说
test.sound是False
?而不是是
-test.sound不会与False
具有相同的标识。但是,如果test.sound:print“yes”
,否则:print“no”
应该打印no.bool(test.sound)
应该是False
+1:bool(fieldFile)
当fieldFile.name
为False时,则是False
。