在django-import-export上过滤

1tuwyuhd  于 2023-01-31  发布在  Go
关注(0)|答案(4)|浏览(185)

我想从我的模型创建csv文件,发送查询字典(过滤器排除)到django-import-export,并从我的模型返回数据。
使用流动的代码,我有所有的模型字段,但我需要过滤他们与查询。

from import_export import resources
from finance.models import Price

class ExportData(resources.ModelResource):

    class Meta:
        model = Price
qojgxg4l

qojgxg4l1#

queryset传递给导出方法:

queryset = Price.objects.exclude(...)
data = ExportData().export(queryset)
data.csv
hrysbysz

hrysbysz2#

要仅过滤导出的文件,而不是管理屏幕中的实际列表,您可以覆盖get_export_queryset方法

from import_export import resources
from import_export.admin import ImportExportMixin

class ProductAdmin(ImportExportMixin, admin.ModelAdmin):
    resource_class = ProductResource

    # Override of ImportExportMixin.get_export_queryset
    # Filter export to exclude Products where is_active is false
    def get_export_queryset(self, request):
            return Product.objects.filter(is_active=True)
omhiaaxx

omhiaaxx3#

您可以在admin.py文件中覆盖resources.ModelResourceexport方法,以在admin上应用筛选器:

from import_export import resources
from finance.models import Price

class ExportData(resources.ModelResource):

    class Meta:
        model = Price

    def export(self, queryset=None, *args, **kwargs):
        # For example only export objects with ids in 1, 2, 3 and 4
        queryset = queryset and queryset.filter(id__in=[1, 2, 3, 4])
        return super(ExportData, self).export(queryset, *args, **kwargs)
3phpmpom

3phpmpom4#

您可以只修改ModelResource类的一个导出方法。

from import_export import resources
from finance.models import Price

class ExportData(resources.ModelResource):

    class Meta:
        model = Price
    
    def export(self, queryset = None, *args, **kwargs):
        queryset = queryset.exclude(id = 5)
        return super().export(queryset, *args, **kwargs)

相关问题