Viewing all your data from your django Admin is not ideal, Sometimes, you may want to export it to a spreedsheet format and perform data analytics or validation.
This is where the django-import-export library comes in handy. It provides an easy way to import and export data in various formats, such as CSV, xlsx and more.
The focus of this tutorial will be on exporting data, and adding export button on admin.
Getting started with Django import export
Start by installing django-import export
pip install django-import-export
Add it to installed apps
# settings.py
INSTALLED_APPS = [
...
'import_export',
]
Create a resource class inside your resource.py
inside your app.
class SampleResource(resources.ModelResource):
class Meta:
model = SampleModel
fields = ('id', 'price', 'description') # optional, only specified fields gets exported, else all the fields
export_order = ('id', 'description', 'price') # optional, describes how order of export
This class defines how the data will be imported and exported. You can also specify fields.
Now add it to admin so go to your admin.py
from django.contrib import admin
from import_export.admin import ExportMixin
from .models import MyModel
from .resources import MyModelResource
@admin.register(MyModel)
class MyModelAdmin(ExportMixin, admin.ModelAdmin):
resource_class = MyModelResource
That's it now you can export data directly from admin panel.
You can also customize like specifying permissions and more. You can read this in their docs
Top comments (0)