Search code examples
djangodjango-import-export

How to using django-import-export to export records sorted by a different column?


I followed documentation in https://django-import-export.readthedocs.io/ to export my Country model using django-import-export package:

class Country(models.Model):
    class Meta:
        db_table = 'country'
        verbose_name_plural = 'countries'
        ordering = ['iso_code']

    iso_code = models.CharField(
        verbose_name='ISO code',
        help_text='2-character ISO country code',
        max_length=2,
        blank=False,
    )
    un_code = models.CharField(
        verbose_name='UN code',
        help_text='3-character UN country code',
        max_length=3,
        blank=False,
    )
    english_name = models.CharField(
        verbose_name='English name',
        help_text='Country name in English',
        max_length=100,
        blank=False,
    )

The resource for country model is:

class CountryResource(resources.ModelResource):
    class Meta:
        model = Country
        export_order = ('id', 'iso_code', 'un_code', 'english_name')

To export the model, I run:

>>> dataset = CountryResource().export()
>>> print(dataset.csv)

The results (partial):

id,iso_code,un_code,english_name
6,AD,AND,Andorra
217,AE,ARE,United Arab Emirates
1,AF,AFG,Afghanistan
8,AI,AIA,Anguilla

Note that the results are ordered by the iso_code column which is given in the Country model's Meta class. Without changing the ordering specified in model's Meta class, however, I want to export the records sorted by another column only during the export. For example, I want to the exported records sorted by id. How could I achieve that? Thanks.


Solution

  • You can redefine get_queryset method and sort queryset as you want

    class CountryResource(resources.ModelResource):
        class Meta:
            model = Country
            export_order = ('id', 'iso_code', 'un_code', 'english_name')
    
        def get_queryset(self):
            return self._meta.model.objects.order_by('id')