Xlwt Excel Экспорт внешних ключей по фактическим значениям / Django

Я экспортирую товары в формат excel с помощью xlwt. Но поля внешнего ключа экспортируются как id.

Как я могу экспортировать поля внешнего ключа с их фактическими значениями?

Я хочу экспортировать поля brand_id и author с их фактическими значениями.

Вот моя модель продукта:

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    author = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='Product Author', null=True)
    brand_id = models.ForeignKey(Brand,on_delete=models.CASCADE, verbose_name="Brand Names")
    name = models.CharField(max_length=255, verbose_name="Product Name")
    barcode = models.CharField(max_length=255, verbose_name="Barcode")
    unit = models.CharField(max_length=255,verbose_name="Product Unit") 

    def __str__(self):
        return self.name

Вот мой вид экспорта:

def export_excel(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = "attachment; filename=Products-" + str(datetime.datetime.now().date())+".xls" 
    wb = xlwt.Workbook(encoding="utf-8")
    ws = wb.add_sheet('Products')
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ["Product Id","Product Author","Product Brand","Product Name","Product Barcode","Product Unit"]

    for col_num in range(len(columns)):
        ws.write(row_num,col_num,columns[col_num],font_style)

    font_style = xlwt.XFStyle()

    rows = Product.objects.filter(author = request.user).values_list("id","author","brand_id","name","barcode","unit")

    for row in rows:
        row_num +=1

        for col_num in range(len(row)):
            ws.write(row_num,col_num,str(row[col_num]), font_style)

    wb.save(response)

Спасибо за вашу помощь. С уважением

Вы можете использовать django-import-export для экспорта данных из модели в файл excel. Эта библиотека также поддерживает другие типы данных, если они понадобятся вам в будущем.

Как описано в документации django-import-export, вы можете создать ресурс, который затем может быть использован как для импорта, так и для экспорта данных в модель. Начните с создания ресурса:

from import_export import resources
from import_export.fields import Field

from .models import Product


class ProductResource(resources.ModelResource):
    author = Field() # for field with foreignkeys you need to add them here
    brand_id = Field() # for field with foreignkeys you need to add them here

    fields = ["id", "author", "brand_id", "name", "barcode", "unit"]

    export_order = ["id", "author", "brand_id", "name", "barcode", "unit"]

    def dehydrate_author(self, product: Product) -> str:
        return f"{product.author.name}" # probably need to adapt the name of the field

    def dehydrate_brand_id(self, product: Product) -> str:
        return f"{product.brand_id.brand}" # probably need to adapt the name of the field

Это также документировано здесь: django-import-export расширенные манипуляции

Теперь вы можете использовать этот ModelResource для экспорта данных в любой поддерживаемый формат, в вашем случае в файл Excel. Импортируйте ваш ресурс, который вы создали ранее, все, что вам нужно сделать, чтобы вернуть его в ваше представление, это следующее:

from django.http import HttpResponse
from .resource import ProductRes

#... other code in your view
project_resource = ProjectResource()
dataset = project_resource.export()
response = HttpResponse(dataset.xlsx, ontent_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response["Content-Disposition"] = 'attachment; filename="projects_export.xlsx"'
Вернуться на верх