导出到csv时,Django导入-导出将Manytomany作为名称而不是ID显示 [英] Django import-export display manytomany as a name instead of ids when exporting to csv

查看:220
本文介绍了导出到csv时,Django导入-导出将Manytomany作为名称而不是ID显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Django import-export将多方列显示为名称列表而不是ID?

How do I display a manytomany column as a list of names instead of ids using Django import-export?

当前,我的模型和resources.py如下所示,并返回了一个cv,其中包含country列的ID列表:

Currently my models and resources.py looks like this and returns a csv with a list of ids for the country column:

models.py

class Country(models.Model):
    name = models.CharField(max_length=50, null=False,
                            blank=False, unique=True)

    def __str__(self):
        return self.name


class Species(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False)
    country = models.ManyToManyField(Country)

    def __str__(self):
        return self.name

resources.py

from import_export import resources,fields
from import_export.widgets import ManyToManyWidget
from .models import Species, Country

class SpeciesResource(resources.ModelResource):
    country=fields.Field(attribute='country', widget=ManyToManyWidget(Country), column_name='Country')
    name = fields.Field(attribute='name', column_name='Name')
    class Meta:
        model = Species
        fields =('name','country')
        export_order = fields

推荐答案

只需在窗口小部件中添加所需字段:

Just add field you need in widget:

widget=ManyToManyWidget(Country, field='name')

这篇关于导出到csv时,Django导入-导出将Manytomany作为名称而不是ID显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆