How To Export Data In Django Using Django-Import-Export Module.
- Shivam Rohilla
- June 12, 2021
- 3 comments
- 937 Views
<meta name="clckd" content="6301244fb7ed470eb1cd6b8c31d01ac4" />
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
First of all, install this module
pip install django-import-export
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.
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
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..
My social media links