Home > Net >  Django import-export, only export one object with related objects
Django import-export, only export one object with related objects

Time:12-11

I have a form which enables a user to register on our website. Now I need to export all the data to excel, so I turned towards the import-export package. I have 3 models, Customer, Reference and Contact. The latter two both have a m2m with Customer. I also created Resources for these models. When I use Resource().export() at the end of my done() method in my form view, it exports all existing objects in the database, which is not what I want.

I tried googling this and only got one result, which basically says I need to use before_export(), but I can't find anywhere in the docs how it actually works.

I tried querying my customer manually like:

customer = Customer.objects.filter(pk=customer.id)

customer_data = CustomerResource().export(customer)

which works fine but then I'm stuck with the related references and contacts: reference_data = ReferenceResource().export(customer.references) gives me an TypeError saying 'ManyRelatedManager' object is not iterable. Which makes sense because export() expects an queryset, but I'm not sure if it's possible getting it that way.

Any help very appreciated!

CodePudding user response:

One way is to override get_queryset(), you could potentially try to load all related data in a single query:

class ReferenceResource(resources.ModelResource):

    def __init__(self, customer_id):
        super().__init__()
        self.customer_id = customer_id

    def get_queryset(self):
        qs = Customer.objects.filter(pk=self.customer.id)
        # additional filtering here
        return qs

    class Meta:
        model = Reference
        # add fields as appropriate
        fields = ('id', )

To handle m2m relationships, you may be able to modify the queryset to add these additional fields.

This isn't the complete answer but it may help you make progress.

  • Related