djangodjango-import-export

how can I add sum rows in django import-export library?


How can I add sum row on the bottom of my table in exported xlsx file?

I don't see anything like that in their doc but maybe you did something similar. I'd like to summarize only the total_price column.

My resource looks like this:

class CERequestResource(resources.ModelResource):

    related_component__service = Field(attribute='related_component__service')
    related_product__title = Field(attribute='related_product__title'')
    related_component__component_name = Field(attribute='related_component__component_name')
    related_component__task_description = Field(attribute='related_component__task_description')
    related_component__position = Field(attribute='related_component__position')
    number_of_units = Field(attribute='number_of_units', column_name='# of Units')
    related_component__margin = Field(attribute='related_component__margin')
    total_price = Field(attribute="total_price")
    
    model = CERequest
    fields = ('id', 'related_component', 'related_product', 'number_of_units', 'total_price', 'margin')

Solution

  • It's really easy - override one method like so:

        def after_export(self, queryset, data, *args, **kwargs):
            total = 0
            for row in data.dict:
                total += Decimal(row["total_price"])
            # this list must equal the width of your row
            # with the total appearing at the same position as
            # 'total_price'
            data.append(["", "", "", "", total, ""])
    

    Note that your example is declared wrong. fields and model need to be under the Meta class declaration:

        class Meta: 
            model = CERequest
            fields = ('id', 'related_component', 'related_product', 'number_of_units', 'total_price', 'margin')