问题
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