Filter on django-import-export

I want to create a csv file form, my model will send a filter exclude dictionary to django-import-export and return data from my model.

using the current code, I have all the model fields, but I need to filter them using a query.

from import_export import resources from finance.models import Price class ExportData(resources.ModelResource): class Meta: model = Price 
+6
source share
3 answers

Pass queryset for export:

 queryset = Price.objects.exclude(...) data = ExportData().export(queryset) data.csv 
+8
source

You can override the export resources.ModelResource method in your admin.py file to apply your filter to 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) 
0
source

To filter only the exported file and not the actual list on the admin screen, you can overwrite the get_export_queryset method

 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) 
0
source

Source: https://habr.com/ru/post/949997/


All Articles