【问题标题】:Unify multiple records of a cvs file - Django统一 cvs 文件的多条记录 - Django
【发布时间】:2021-03-30 16:56:09
【问题描述】:

我正在从数据库生成一个 CSV 文件,但我想将一些记录统一在一行中。

原始 CSV 如下所示:

Model Name Configurations_variatons
MODEL-1 Lipstick Grand Rouge Mate cod=23432, color=23432-150
MODEL-1 Lipstick Grand Rouge Mate cod=23770, color=23770-151

我希望每个模型只显示一行,但要统一 Configurations_variatons 列:

Model Name Configurations_variatons
MODEL-1 Lipstick Grand Rouge Mate cod=23432, color=23432-150 - cod=23770, color=23770-151

生成cvs文件的代码:

def cvs_file_generator(request):

    # Get all data from UserDetail Databse Table
    products = Products.objects.all()

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="csv_database_write.csv"'

    writer = csv.writer(response)
    writer.writerow(['Model', 'Name', 'Configurations_variatons'])

    for product in products:
        writer.writerow([product.model, product.name, product.configurations_variatons])

    return response

【问题讨论】:

    标签: python python-3.x django csv django-views


    【解决方案1】:

    我建议您查看在 Django 中进行分组的方法,并使用按模型和名称分组来创建您想要的表。 您可以使用 python 代码来完成,但效率极低。
    即使很难在不访问您的数据库的情况下创建 SQL 查询,我建议类似 products = Products.objects.raw('SELECT * FROM <your Django app name>_products GROUP BY Model, Name') 更多信息请见How to query as GROUP BY in django?How to use GROUP BY to concatenate strings in MySQL

    【讨论】:

    • 谢谢,让我开阔了眼界
    猜你喜欢
    • 2011-10-18
    • 2021-06-18
    • 1970-01-01
    • 2011-02-14
    • 2017-10-31
    • 2021-01-22
    • 2017-02-24
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多