【问题标题】:How to access a ForeignKey Object's attribute on a dynamic basis如何动态访问 ForeignKey 对象的属性
【发布时间】:2018-08-05 09:10:34
【问题描述】:

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

【问题讨论】:

    标签: python django django-models django-contenttypes


    【解决方案1】:

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

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

    if field.many_to_one:
        print(field.related_model)
    

    【讨论】:

    • 工作得很好!谢谢。
    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 2011-08-10
    • 2019-09-01
    • 2011-01-18
    • 2016-10-13
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多