DEV Community

Cover image for How to get exact value of foreignkey in django-import-export
Shivam Rohilla
Shivam Rohilla

Posted on

How to get exact value of foreignkey in django-import-export

Hello Devs, In this blog I'm gonna tell you how can you get exact values of Foreignkey-Field in django-import-export

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
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..

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

Thank You

Top comments (0)