Django import-export display manytomany as a name instead of ids when exporting to csv

青春壹個敷衍的年華 提交于 2019-12-11 06:26:25

问题


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

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

回答1:


Just add field you need in widget:

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


来源:https://stackoverflow.com/questions/56289812/django-import-export-display-manytomany-as-a-name-instead-of-ids-when-exporting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!