Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 723
ccsv Avatar asked Oct 29 '25 14:10

ccsv


1 Answers

Just add field you need in widget:

widget=ManyToManyWidget(Country, field='name')
like image 110
Sergey Pugach Avatar answered Oct 31 '25 05:10

Sergey Pugach