DEV Community

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

Posted on

3 1

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

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay