如何动态访问外键对象的属性

How to access a ForeignKey Object's attribute on a dynamic basis

我目前正在尝试在 for 循环中访问 ForeignKey to 属性,因为我要求它是动态的。 django 的文档和在线搜索都没有提供任何有用的结果。 这是我正在使用的:带有 Django CMS 3.5.2 和 Django Countries 包的 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

如您所见,没有名为 to 属性 。那是 ForeignKey 初始值设定项的 参数 的名称。由于参数可以是字符串模型引用或 "self",代表实际模型目标的属性应该具有不同的名称是有道理的。

Field attribute reference 定义了用于内省字段对象的 API。你想要的是这样的:

if field.many_to_one:
    print(field.related_model)