Search code examples
djangodjango-import-export

Django ImportExport dynamic fields


I am using Django ImportExport. I would like to export all entries from a model called Room. Each Room can have one to m (upper bound of 20) Tables in it.

So I have the following resource:

class RoomResource(resources.ModelResource):
    table1 = Field()
    table2 = Field()
    # ...
    tableM = Field()  

    class Meta:
        model = Room
        fields = ('table1', 'table2', 'tableM')

    @staticmethod
    def _dehydrate_table(room, table_number):
        if not room.table_number.count() > number - 1:
            return ''
        return getattr(room.table_number.all()[number - 1], 'person_count', '')
    
 
    def dehydrate_table1(self, room):
        return self._dehydrate_table(room, 1)

    def dehydrate_table2(self, instance):
        return self._dehydrate_table(room, 2)

    def dehydrate_tableM(self, instance):
        return self._dehydrate_table(room, M)

This works fine (because my M has an upper bound of 20) but seems to be much less dynamically solved as it should be.

So I think I need to do three things:

1.) Set fields = (...) dynamically

2.) Set the class attribute tableM = Field() dynamically

3.) Set the dehydrate_tableM() dynamically.

I tried to do this over the __init__ method, but this adds the fields to the instance dict and not to the class dict, which does not work.

So how can I solve this?


Solution

  • Solved it by overwriting def get_fields(self, **kwargs). There you have to find the entry with the most relations and add a field for every relation:

    max_table_count = max([qs.tables.count() for qs in self.get_queryset()])
    for current in range(1, max_table_count + 1):
        new_field = Field(column_name=f'Table {current}')
        self.fields[f'table_{current}'] = new_field