Как я могу добавить сумму строк в библиотеке импорта-экспорта django?
Как добавить строку суммы внизу таблицы в экспортированный файл xlsx?
Я не вижу ничего подобного в их документации, но, возможно, вы сделали что-то похожее. Я хотел бы суммировать только столбец total_price
.
Мой ресурс выглядит следующим образом:
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')
Это очень просто - переопределите один метод следующим образом:
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, ""])
Обратите внимание, что ваш пример объявлен неправильно. fields
и model
должны находиться под объявлением класса Meta
:
class Meta:
model = CERequest
fields = ('id', 'related_component', 'related_product', 'number_of_units', 'total_price', 'margin')