django.import-export ImportExportMixin定制

lmvvr0a8  于 2023-05-08  发布在  Go
关注(0)|答案(1)|浏览(107)

我正在使用ImportExportMixin将导入导出按钮添加到我的管理页面:

我这样写:

from django.contrib import admin
from .models import *
from import_export.admin import ImportExportMixin

class PlayerAdmin(ImportExportMixin,admin.ModelAdmin):
    list_display = [field.name for field in Player._meta.fields]

admin.site.register(Player,PlayerAdmin)

当我执行此导出时,我得到如下内容:
[{"id": 1, "name": "player1", "date_birth": "1997-01-01", "tshirtnumber": 19, "club": 1, "poste": "ST"}]
俱乐部是ForeingKey,我想要俱乐部的名称,而不是ID。那该怎么办请我需要同样的东西为进口我的意思是我想进口球员与他们的俱乐部名称。
我期待:
[{"id": 1, "name": "player1", "date_birth": "1997-01-01", "tshirtnumber": 19, "club": "chelsea", "poste": "ST"}]

hts6caw3

hts6caw31#

对于导出,您可以在资源的fields列表中定义关系:

class PlayerResource(ModelResource):
    class Meta:
        model = Player
        # add all your export fields
        fields = ("id", "name", "club__name")

要导入关系,请声明ForeignKeyWidget

class PlayerResource(ModelResource):
     # values here might be different depending on your model
     club = fields.Field(
        column_name='club',
        attribute='club',
        widget=ForeignKeyWidget(Club, field='name'))

    class Meta:
        model = Player
        # ...

相关问题