一个类中的空字段

时间:2017-03-18 17:09:58

标签: django field

对于目标字段,我想在类中创建一个函数。只要字段income_sourceEmployed不同,该函数就会清空除目标字段之外的所有字段。我怎么能要求在课堂上清空每个领域?

提前致谢!

@python_2_unicode_compatible
class EmployerProfile(AbstractAddress):
    income_source = models.CharField(_('Income source'), max_length=20,
                                 choices=settings.LOANWOLF_INCOME_SOURCE_CHOICES,
                                 default='employed')


    company_name = models.CharField(_('Company name'),
                                    max_length=50, blank=True, null=True)
    phone = PhoneField(_('Phone'), max_length=50, blank=True, null=True)
    phone_extension = models.CharField(_('Extension'), max_length=10,
                                       blank=True, null=True)
    job_title = models.CharField(_('Job title'), max_length=50, blank=True,
                                 null=True)
    date_hired = models.DateField(_('Date hired'), blank=True, null=True)
    supervisor_name = models.CharField(_('Supervisor name'), max_length=50,
                                       blank=True, null=True)
    has_missing_fields = models.BooleanField(_('Has missing informations'),
                                             default=True)
    manual_validation = GenericRelation(ManualFieldValidation)

1 个答案:

答案 0 :(得分:0)

如果要根据字段清除这些内容,最好在保存模型实例之前执行此操作。此外,我们不想清除所有字段,最好明确哪些字段要清除。

这是未经测试的,但请告诉我这对您有何影响:

def save(self, *args, **kwargs):
    if self.company_name != "employed":
        to_empty = [ 
            "company_name",
            "phone",
            "phone_extension",
            "job_title",
            "date_hired",
            "supervisor_name",
        ]
        for field_name in to_empty:
            setattr(self, field_name, None)
    super(EmployerProfile, self).save(*args, **kwargs)

如果你正在使用Python 3,那么最后一行就是:

    super().save(*args, **kwargs)