[英]Django - FileField check if None
我有一个带有可选文件字段的模型
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
如何检查是否有文件集?
if test.sound.name:
print "I have a sound file"
else:
print "no sound"
此外, FieldFile
的布尔值在没有文件时将为 False: bool(test.sound) == False
当test.sound.name
为bool(test.sound) == 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.