Django - FileField 检查是否为 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
我该如何检查是否有文件被设置呢?
2 个回答
0
根据这个回答,你可以试试这个方法:
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)
125
if test.sound.name:
print "I have a sound file"
else:
print "no sound"
另外,当没有文件时,FileField
的布尔值会是False:也就是说,当test.sound.name
没有值时,bool(test.sound)
的结果是False。