【问题标题】:Django - FileField check if NoneDjango - FileField 检查是否没有
【发布时间】:2012-02-09 15:32:04
【问题描述】:

我有一个带有可选文件字段的模型

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

如何检查是否有文件集?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:
    if test.sound.name: 
         print "I have a sound file"
    else:   
         print "no sound"
    

    此外,FieldFile 的布尔值在没有文件时将为 False:bool(test.sound) == Falsetest.sound.name 为假时。

    【讨论】:

    • 哪个布尔值?你是说test.sound is False 吗?
    • 不是is - test.sound 与False 的身份不同。但是,if test.sound: print "yes"else: print "no" 应该打印 no。 bool(test.sound) 应该是 False
    • +1:bool(fieldFile)False,而 fieldFile.name 是假的。
    【解决方案2】:

    根据这个answer来自另一个问题,你可以试试这个:

    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)
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2010-12-10
      • 2013-11-28
      • 2019-08-09
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多