显示使用元类的所有fied的列表

时间:2017-03-18 19:04:48

标签: python django

由于我在一个类中有561个字段,我们是否可以使用元类来帮助我显示此类中所有字段的列表?

这是我到目前为止所做的:

@python_2_unicode_compatible
class EmployerProfile(AbstractAddress):
    customer = models.OneToOneField(
        CustomerProfile, verbose_name=_('Customer'),
        related_name='employerprofile')

    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)

这是我想要使用元类

修改的函数
def clean_fields(self):
        if income_source != 'Employed':
            to_empty = [
                "company_name",
                "job_title",
                "date_hired",
                "supervisor_name",
                "phone",
                "phone_extension",
                "civic_number",
                "street",
                "address_line_2",
                "city",
                "state",
                "zip_code",
                ...
            ]
            for field_name in to_empty:
                setattr(self, field_name, None)
        super(EmployerProfile, self).save(*args, kwargs)

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以获取此类型号的字段名称:

field_names = [f.name for f in EmployerProfile._meta.get_fields()]

或者如果你想要字段实例,只需:

field_inst = EmployerProfile._meta.get_fields()

在模型中你可以这样做:

class EmployerProfile(AbstractAddress):
    # model fields

    @classmethod
    def field_names(cls):
        return [f.name for f in cls._meta.get_fields()]