Python 使用元类显示所有域的列表
因为我在一个类中有561个字段,我们可以使用一个元类来帮助我显示这个类中所有字段的列表吗 以下是我迄今为止所做的工作:Python 使用元类显示所有域的列表,python,django,Python,Django,因为我在一个类中有561个字段,我们可以使用一个元类来帮助我显示这个类中所有字段的列表吗 以下是我迄今为止所做的工作: @python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerp
@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)
提前谢谢 您可以获得如下模型的字段名:
field_names = [f.name for f in EmployerProfile._meta.get_fields()]
class EmployerProfile(AbstractAddress):
# model fields
@classmethod
def field_names(cls):
return [f.name for f in cls._meta.get_fields()]
或者,如果需要字段实例,只需执行以下操作:
field_inst = EmployerProfile._meta.get_fields()
在您的模型中,您可以这样做:
field_names = [f.name for f in EmployerProfile._meta.get_fields()]
class EmployerProfile(AbstractAddress):
# model fields
@classmethod
def field_names(cls):
return [f.name for f in cls._meta.get_fields()]
请发布到目前为止您所尝试的内容。@James完成了吗?我对这个方法有点熟悉,但我必须在我的类中创建一个元类吗。您可以修改函数以使用此方法吗?所以,您的意思是希望从
Meta
类内部查看模型字段名称?不,不完全是这样。我想我需要创建一个元类来使用field\u names=[f.name for f in EmployeerProfile.\u meta.get\u fields()]
。不,你不需要为此创建meta
类。也许这是一个愚蠢的问题,但我想知道我是否必须只编写income\u source
、customer.income\u source
或<代码>客户(收入来源=收入来源…)?