本文介绍了导出到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显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!