【问题标题】:How to using django-import-export to export records sorted by a different column?如何使用 django-import-export 导出按不同列排序的记录?
【发布时间】:2017-07-02 23:30:59
【问题描述】:

我按照https://django-import-export.readthedocs.io/ 中的文档使用django-import-export 包导出我的国家/地区模型:

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,
    )

国家模型的资源是:

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

要导出模型,我运行:

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

结果(部分):

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

请注意,结果按 Country 模型的 Meta 类中给出的 iso_code 列排序。但是,在不更改模型 Meta 类中指定的顺序的情况下,我只想在导出期间导出按另一列排序的记录。例如,我想将导出的记录按id 排序。我怎么能做到这一点?谢谢。

【问题讨论】:

    标签: django django-import-export


    【解决方案1】:

    您可以重新定义get_queryset 方法并根据需要对查询集进行排序

    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') 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2022-07-18
      相关资源
      最近更新 更多