是否可以根据方法的输出将Django BooleanField默认值设置为True或False?

2024-10-01 17:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何设置默认值,但我不确定是否可以通过方法定义它。在

@mrdurant:一开始是范围问题,我在调用函数之前有一个布尔字段,我把它放在函数之后,但是现在我得到了以下错误:

has_photo只接受1个参数(给定0)”

我试着传递论点,但没能使它发挥作用。在

注意:has_photo函数计算另一个类(HousingPhotos)中是否保存了任何内容。在

class Housing(models.Model):
    h_type = models.CharField(max_length=16)
    transaction = models.CharField(max_length=16)
    pub_date = models.DateTimeField('publicado')

    def has_photo(self):
        test = Housing(self.pk)
        if test.housingphotos_set.count() == 0:
            return False
        else:
            return True
    has_photo.boolean= True
    show_photo = models.BooleanField(default=has_photo)

Tags: 方法函数testselftruereturn定义models
2条回答

因为has_photo是一个方法,您需要能够将self作为第一个参数传递(django假设一个常规函数)。您可以将其从类中取出作为常规函数,也可以构建一个使用适当参数调用的函数:

default=lambda: self.has_photo()

最好将其表示为更详细的函数/方法调用

您可以在默认值中设置可调用的

def bar():
    return boolean

your_boolean_field = models.BooleanField(default=bar)

或重写模型的保存方法。在

^{pr2}$

相关问题 更多 >

    热门问题