使用 DJango 和 import_export 导出数据,列重复

Exporting data with DJango and import_export, columns are duplicated

我正在创建一个 Django 应用程序,我正在使用 import_export 包。我已经使用同时设置了 attributecolumn_name 的字段定义了我的资源。当我导出到 xlsx(或 csv)时,我得到 attribute 作为 header 的列,以及 column_name header.

的重复列

Meta 子类中包含 fields 属性不会影响此行为。

# app\resources.py

class RoleResource(resources.ModelResource):
    name = Field(attribute="name", column_name="Sales Role")
    role = Field(attribute="default_role" column_name="System Role")
    plan = Field(attribute="default_plan" column_name="System Plan")

    class Meta:
        model = Role
        # fields = ('name', 'default_role', 'default_plan') # commenting this doesn't change behavior

注释掉 Meta.fields 的最终输出有 6 列:Sales Role、System Role、System Plan、id、default_role、default_plan.

未注释 Meta.fields 的最终输出有 5 列:销售角色、系统角色、系统计划、default_role、default_plan。

我认为 column_name 是装饰品。为什么我得到两个重复的列?

Why am I getting two duplicated columns?

因为您在 fields 元选项中混合了已声明的属性和字段,并且它们具有不同的名称。

修复:重命名声明的字段以匹配所需的名称:

class RoleResource(resources.ModelResource):
    name = Field(attribute="name", column_name="Sales Role")
    default_role = Field(attribute="default_role" column_name="System Role")
    default_plan = Field(attribute="default_plan" column_name="System Plan")

    class Meta:
        model = Role
        fields = ('name', 'default_role', 'default_plan') 

发生的事情是,当资源被实例化时,逻辑会查看哪些字段已经 declared on the resource,并将它们添加到本地字段字典中。然后它对声明的字段执行相同的操作。属性名称用作键,因此如果它们不同,则会得到重复项。

例如:

声明的字段匹配字段选项:

class BookResource(resources.ModelResource):
    # declared names match `fields`
    name = Field(attribute="name", column_name="Book Name")
    author_email = Field(attribute="author_email", column_name="Author Email")

    class Meta:
        model = Book
        fields = ('id', 'name', 'author_email')

输出:

Book Name |Author Email     |id
----------|-----------------|--
Foo       |email@example.com|1 

声明的字段具有不同的名称:

class BookResource(resources.ModelResource):
    # declared fields are different
    some_other_name = Field(attribute="name", column_name="Book Name")
    some_other_author_email = Field(attribute="author_email", column_name="Author Email")

    class Meta:
        model = Book
        fields = ('id', 'name', 'author_email')

输出:

Book Name |Author Email     |id|name      |author_email     
----------|-----------------|--|----------|-----------------
Foo       |email@example.com|1 |Foo       |email@example.com

fields 声明然后用作白名单来确定哪些字段出现在输出中。如果您没有 fields 声明,则会显示所有字段。