Python 如何访问ForeignKey对象';在动态的基础上定义属性

Python 如何访问ForeignKey对象';在动态的基础上定义属性,python,django,django-models,django-contenttypes,Python,Django,Django Models,Django Contenttypes,我目前正试图在for循环中访问ForeignKeyto属性,因为我要求它是动态的。django的文档和在线搜索都没有提供任何有用的结果。 这里是我正在使用的:Django 1.11和Django CMS 3.5.2以及Django Countries包。错误消息是: AttributeError: 'ForeignKey' object has no attribute 'to 但是,访问字段的名称或详细名称,甚至选择属性(对于charFields或IntegerFields)都可以 mode

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

AttributeError: 'ForeignKey' object has no attribute 'to
但是,访问字段的名称或详细名称,甚至选择属性(对于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”
,因此表示实际模型目标的属性应该具有不同的名称是有意义的

定义用于内省字段对象的API。你所追求的是:

if field.many_to_one:
    print(field.related_model)

如您所见,没有名为
to
的属性。这是
ForeignKey
初始值设定项的参数名称。由于参数可以是字符串模型引用,或
“self”
,因此表示实际模型目标的属性应该具有不同的名称是有意义的

定义用于内省字段对象的API。你所追求的是:

if field.many_to_one:
    print(field.related_model)

很好用!谢谢,很好用!谢谢