Search code examples
djangodjango-import-export

Denormalising relationships with django-import-export


I have room booking application with a Booking model that has a simple ForeignKey relationship to my Room model. Here's a super-brief idea of what I'm dealing with:

class Room(..):
    floor = models.IntegerField()
    number = models.IntegerField()
    ...

class Booking(..):
    room = models.ForeignKey('Room')
    ...

I've been using django-import-export on the Booking model to let the admin take backups of this data in a way they can import into Excel. It's been really useful for quickly giving them data on demand without costing them my time.

My problem is that the room relationship is ignored; it pumps out the room_id instead of following the relationship. I understand how this makes sense for the sake of importing data but for all practical external purposes, the Room's primary_key is completely useless. People looking at Booking data need to know which floor and number Room it's for.

Is there a simple way to add extra data to the django-import-export's data to essentially denormalise those fields through?


Solution

  • See Getting started in documentation.

    When defining ModelResource fields it is possible to follow model relationships:

    class BookResource(resources.ModelResource):
    
        class Meta:
            model = Book
            fields = ('author__name',)
    

    In your case fields would be ('room__floor', 'room__number',)