{"id":2477,"library":"django-import-export","title":"django-import-export","description":"django-import-export is a versatile Django application and library for importing and exporting data, with seamless integration into the Django admin interface. It supports various data formats like CSV, JSON, and Excel, and allows for robust customization through `Resource` classes for complex data mapping and transformations. The project maintains active development with regular patch releases and significant updates approximately once a year.","status":"active","version":"4.4.0","language":"en","source_language":"en","source_url":"https://github.com/django-import-export/django-import-export","tags":["django","import","export","data","admin","csv","excel","json"],"install":[{"cmd":"pip install django-import-export","lang":"bash","label":"Install core library"},{"cmd":"pip install django-import-export[pandas]","lang":"bash","label":"Install with Pandas support (optional)"}],"dependencies":[{"reason":"Core framework requirement, as it is a Django application.","package":"django","optional":false},{"reason":"Backend for data handling, format conversions.","package":"tablib","optional":false},{"reason":"Required for Excel (.xlsx) file support.","package":"openpyxl","optional":false},{"reason":"Optional dependency for advanced data manipulation and reading/writing certain formats.","package":"pandas","optional":true}],"imports":[{"symbol":"ModelResource","correct":"from import_export.resources import ModelResource"},{"symbol":"Field","correct":"from import_export.fields import Field"},{"symbol":"ForeignKeyWidget","correct":"from import_export.widgets import ForeignKeyWidget"},{"symbol":"ImportExportModelAdmin","correct":"from import_export.admin import ImportExportModelAdmin"}],"quickstart":{"code":"import os\nimport django\nfrom django.conf import settings\nfrom import_export import resources\nfrom import_export.fields import Field\nfrom import_export.widgets import ForeignKeyWidget\n\n# Minimal Django setup for standalone script\nif not settings.configured:\n    settings.configure(\n        INSTALLED_APPS=[\n            'django.contrib.auth',\n            'django.contrib.contenttypes',\n            'django.contrib.sessions',\n            'django.contrib.admin',\n            'import_export',\n            'my_app', # Placeholder for your app\n        ],\n        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},\n        DEBUG=True,\n        USE_TZ=True,\n        TIME_ZONE='UTC',\n        SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'super-secret-key-for-testing'),\n        TEMPLATES=[{\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [],\n            'APP_DIRS': True,\n        }],\n        ROOT_URLCONF='django_import_export.urls', # Dummy URLconf required by django.setup()\n    )\n    django.setup()\n\nfrom django.db import models\n\n# 1. Define your Django Models (example)\nclass Category(models.Model):\n    name = models.CharField(max_length=100, unique=True)\n    def __str__(self): return self.name\n    class Meta: app_label = 'my_app'\n\nclass Product(models.Model):\n    name = models.CharField(max_length=100)\n    price = models.DecimalField(max_digits=10, decimal_places=2)\n    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)\n    def __str__(self): return self.name\n    class Meta: app_label = 'my_app'\n\n# Need to create tables for these models in the in-memory DB for the example\nfrom django.db import connection\nwith connection.schema_editor() as schema_editor:\n    schema_editor.create_model(Category)\n    schema_editor.create_model(Product)\n\n# 2. Define a Resource for your Model\nclass ProductResource(resources.ModelResource):\n    category = Field(\n        column_name='category_name',\n        attribute='category',\n        widget=ForeignKeyWidget(Category, 'name') # Match category by name during import/export\n    )\n\n    class Meta:\n        model = Product\n        fields = ('id', 'name', 'price', 'category',) # Fields to include\n        export_order = ('id', 'name', 'price', 'category',) # Order for export\n\n# 3. Use the Resource to export data programmatically\ncategory_electronics = Category.objects.create(name='Electronics')\nProduct.objects.create(name='Laptop', price=1200.00, category=category_electronics)\nProduct.objects.create(name='Mouse', price=25.00, category=category_electronics)\n\nproduct_resource = ProductResource()\ndataset = product_resource.export()\n\nprint(\"\\n--- Exported CSV data ---\")\nprint(dataset.csv)\n","lang":"python","description":"This quickstart demonstrates how to define a `ModelResource` for a Django model and perform a programmatic export. It includes a minimal Django setup to make the example runnable independently, showing how to handle related `ForeignKey` fields using `ForeignKeyWidget` for clear human-readable mapping during export and import."},"warnings":[{"fix":"Review the official changelog for v4.0.0. Update `base_queryset` to `get_queryset`. Adjust `fields`, `exclude`, `widgets` definitions if relying on previous implicit behaviors. Ensure Python and Django versions meet new requirements.","message":"Version 4.0.0 introduced significant breaking changes: `base_queryset` was removed (use `get_queryset`), `export_order` default changed, and `fields`, `exclude`, `widgets` behavior was refined. Additionally, Python < 3.9 and Django < 3.2 are no longer supported.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update custom `import_obj` and `save_row` implementations to handle the `(obj, new)` return signature. Rename any overrides of `get_data_for_export` to `get_export_data`.","message":"In v4.0.0, the `import_obj` and `save_row` methods now return a tuple `(obj, new)` to indicate if a new object was created. Also, `get_data_for_export` was renamed to `get_export_data`.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"For related fields, use `Field(attribute='related_field', widget=ForeignKeyWidget(RelatedModel, 'unique_field_name'))` or `ManyToManyWidget`.","message":"When dealing with `ForeignKey` or `ManyToMany` fields, you must explicitly define a `Field` with a `ForeignKeyWidget` or `ManyToManyWidget` and specify the `field` argument (e.g., `'name'`, `'slug'`). Otherwise, the library will attempt to match by primary key (ID) during import, which is often not desired.","severity":"gotcha","affected_versions":"All"},{"fix":"For export, override `get_queryset` in your `Resource` to add `.iterator()`: `return super().get_queryset().iterator()`. For import, consider processing data in chunks or pre-processing the file to reduce memory footprint. Always use `dry_run` before final imports.","message":"Importing or exporting very large datasets can lead to memory exhaustion. By default, `queryset` fetching might load all objects into memory.","severity":"gotcha","affected_versions":"All"},{"fix":"Always set `resource_class = YourResource` in your `ModelAdmin` class inheriting from `ImportExportModelAdmin`.","message":"Since v3.0.0, `ImportExportMixin` and `ImportExportModelAdmin` strictly require the `resource_class` attribute to be explicitly set. Inferring the `Resource` from `_meta.model` is no longer supported.","severity":"deprecated","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}