如何动态访问ForeignKey对象的属性

时间:2018-08-05 09:10:35

标签: python django django-models django-contenttypes

我目前正在尝试在for循环中访问ForeignKey to属性,因为我要求它是动态的。 django的文档和在线搜索都没有提供任何有用的结果。 我正在使用的是:带有Django CMS 3.5.2和Django Country软件包的Django 1.11。错误消息是:

AttributeError: 'ForeignKey' object has no attribute 'to

但是,可以访问字段的名称或verbose_name甚至选择属性(对于charFields或IntegerFields)。

models.py

company = models.ForeignKey(verbose_name=_('Company'), blank=False, null=False, to='accounts.CompanyName',
                            on_delete=models.CASCADE)

views.py

def generate_view(instance):
    model = apps.get_model(app_label='travelling', model_name=str(instance.model))
    data = dict()
    field_list = eval(instance.fields)
    fields = model._meta.get_fields()
    output_list = list()

    for field in fields:
        for list_field in field_list:
            if field.name == list_field:
                options = list()
                if field.__class__.__name__ == 'ForeignKey':
                    print(field.to) # Here's the error
                elif field.__class__.__name__ == 'CountryField':
                    for k, v in COUNTRIES.items():
                        options.append((k, v)) # Works properly
                elif field.__class__.__name__ == 'ManyToManyField':
                    pass # Yields the same issues as with foreign keys

                output_list.append({
                    'name': field.name,
                    'verbose': field.verbose_name,
                    'options': options,
                    'type': field.__class__.__name__
                })

    return data

1 个答案:

答案 0 :(得分:3)

如您所见,没有一个名为to属性。这就是ForeignKey初始化程序的参数的名称。由于参数可以是字符串模型引用或"self",因此代表实际模型目标的属性应具有不同的名称。

Field attribute reference定义用于自省字段对象的API。您所追求的是这样的:

if field.many_to_one:
    print(field.related_model)