DEV Community

Cover image for How to Export Data in Django using django-import-export Module.
Shivam Rohilla
Shivam Rohilla

Posted on • Edited on

How to Export Data in Django using django-import-export Module.

Hello Devs, In this tutorial I'm gonna teach you how to use django-import-export module, I write this blog because I faced some errors during my project so that's why I write this blog and want to give you information or my code..

Github Link:- https://github.com/ShivamRohilllaa/django-import-export
Enter fullscreen mode Exit fullscreen mode

Django-import-Export

First of all install this module

pip install django-import-export

Enter fullscreen mode Exit fullscreen mode

Now add this in your installed apps

# settings.py
INSTALLED_APPS = (
    ...
    'import_export',
)
Enter fullscreen mode Exit fullscreen mode

How to implement this in your Admin Panel

Admin.py
from import_export.admin import ImportExportModelAdmin

class ModelnameAdmin(ImportExportModelAdmin):
    model = Modelname

Enter fullscreen mode Exit fullscreen mode

now register this model and you will se import or export button in your admin panel, just click on export and export the complete model data.

How to get exact values of Foreignkey-Field in django-import-export

This value can be achieved by dehydratemethod in django-import-export, I'll show you the code how you can do this.

Create two Models and connect them with foreignkey

class author(models.Model):
    auth = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=100)

    def __str__(self):
        return self.full_name

class publisher(models.Model):
    auth = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=100)

    def __str__(self):
        return self.full_name

class book(models.Model):
    writer = models.ForeignKey(author, on_delete=models.CASCADE)
    publisher = models.ForeignKey(publisher, on_delete=models.CASCADE)
    bookname = models.CharField(max_length=50)
    qty = models.IntegerField()

    def __str__(self):
        return self.bookname
Enter fullscreen mode Exit fullscreen mode

Now, write this code in your admin.py file

from .models import *
from import_export.fields import Field
from import_export import resources


class BookResource(resources.ModelResource):
    writer = Field()
    publisher = Field()

    class Meta:
        model = book
        exclude = ['qty']

    def dehydrate_writer(self, book):
        return '%s by %s' % 
              (book.bookname,book.writer.auth.username)

    def dehydrate_publisher(self, book):
        return '%s by %s' % 
             (book.bookname,book.publisher.auth.username)

class BookAdmin(ExportMixinAdmin):
    resource_class = BookResource


admin.site.register(book, BookAdmin)

Enter fullscreen mode Exit fullscreen mode

So, this is how you can get exact values of your foreignkey in your spreadsheet..

Thank You

Top comments (0)