<meta name="clckd" content="6301244fb7ed470eb1cd6b8c31d01ac4" />
Django

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

Django-import-Export

First of all, install this module

pip install django-import-export

 

How to implement this in your Admin Panel

Admin.py

from import_export.admin import ImportExportModelAdmin

class ModelnameAdmin(ImportExportModelAdmin):

    model = Modelname

now register this model and you will see the 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 dehydrate method 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

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)

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

Thank You 

0 Comments
  • No Reviews Yet

Leave a Reply
Please Sign In For Comment.
Login or Signup
Shivam Rohilla
Hi, I'm Shivam Rohilla

Hi! My name is Shivam Rohilla. I am a Full Stack Web Developer, and I'm very passionate and dedicated to my work. With 2 years experience as a professional Full Stack Web Developer.

Follow Me:-

My social media links