python - 有没有通用的方法来实现列名称?

标签 python django django-import-export

我正在尝试以通用方式实现 django-import-export 库。

在 Meta 类中设置 fields 属性时,无法设置列名称。当直接在 ModelResource 上设置 Field() 时,这是可能的。但据我所知,您无法以通用方式创建它们。

这是我已经拥有的:

def create_resource(django_model, model_fields):
    class ModelResource(resources.ModelResource):
        class Meta:
            model = django_model
            fields = model_fields

    return ModelResource()

最佳答案

我找到了解决方案。

from import_export import resources
from import_export.fields import Field

def create_resource(django_model, django_fields):
    class ModelResource(resources.ModelResource):
        class Meta:
            model = django_model
            fields = ()

    resource = ModelResource()
    for attribute, name in django_fields:
        resource.fields[attribute] = Field(attribute=attribute, column_name=name)

    return resource

create_resource 将使用 django_fields 参数中的所有 Fields 创建 ModelResourcedjango_fields 变量将如下所示:

django_fields = [
            ("id", "ID"),
            ("first_name", "First name"),
            ("last_name", "Last name"),
            ("group__name", "Group name"),
        ]

关于python - 有没有通用的方法来实现列名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723319/

相关文章:

python - Django-Import-Export导入CSV,如何处理u'\\ufeff,UTF-8 BOM问题?

python - 在 python 中获取屏幕顶部的 tkinter Messagebox

Django 标签

python - Python中的关键字提取

css - 使用替代设置文件夹设置向 Django 显示在哪里可以找到我的静态文件

python - django-import-export:如何使用没有键但有名称的外键导入数据?

python - django-import-export 外部管理员

Python 警告 - 删除自定义警告消息末尾的原始警告输出的任何方法

python - 在Python中查找单词的第一个元音

python - 使用 "import <module>"或 "from <module> import <func>"效率更高吗?