Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Exporting models data in Django
In this article, we will see how to export model data in .csv format. Sometimes, you might need to export your model data in different formats such as .csv, json, or .xlsx for further work or reporting. Django provides an elegant solution using the django-import-export package.
We will create a Django project with a simple model and configure it to enable data export functionality through the Django admin interface.
Installation and Setup
First, install the required package ?
pip install django-import-export
Add the library to your project's INSTALLED_APPS in settings.py ?
INSTALLED_APPS += ['import_export']
Creating the Model
Create a simple model in models.py for demonstration ?
from django.db import models
class StudentData(models.Model):
name = models.CharField(max_length=100)
standard = models.CharField(max_length=100)
section = models.CharField(max_length=100)
def __str__(self):
return self.name
This creates a basic student model with name, standard, and section fields.
Configuring Admin Interface
In admin.py, configure the import-export functionality ?
from django.contrib import admin
from .models import StudentData
from import_export import resources
from import_export.admin import ImportExportModelAdmin
class StudentResource(resources.ModelResource):
class Meta:
model = StudentData
class StudentAdmin(ImportExportModelAdmin):
resource_class = StudentResource
list_display = ['name', 'standard', 'section']
admin.site.register(StudentData, StudentAdmin)
The StudentResource class defines how the model should be exported, while StudentAdmin integrates the export functionality into the Django admin.
Using the Export Feature
After running migrations and creating a superuser, navigate to the admin interface at http://127.0.0.1:8000/admin. You will see the StudentData model with additional import/export buttons.
To export data:
- Go to the StudentData section in admin
- Add some sample data entries
- Click the "Export" button
- Choose your desired format (CSV, JSON, XLSX, etc.)
- Download the exported file
Customizing Export Fields
You can customize which fields to export by modifying the resource class ?
class StudentResource(resources.ModelResource):
class Meta:
model = StudentData
fields = ('id', 'name', 'standard') # Export only specific fields
export_order = ('id', 'name', 'standard') # Control field order
Conclusion
The django-import-export package provides a powerful and user-friendly way to export Django model data. It integrates seamlessly with the admin interface and supports multiple formats, making data export tasks much simpler than writing custom scripts.
