1

I'm generating a CSV file from a database but I want to unify some records in only one row.

The original CSV look like this:

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

And I want to show with only one row per model but unifying the Configurations_variatons column:

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

The code to generate the cvs file:

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
Burhan Ali
  • 2,258
  • 1
  • 28
  • 38

1 Answers1

0

I suggest you check out ways to group by in Django and use group by Model and Name to create the table you want. You can do it using python code, but it will be extremely inefficient.
even though it is hard to create a SQL query without access to your database, I suggest something like products = Products.objects.raw('SELECT * FROM <your Django app name>_products GROUP BY Model, Name') for more information, please see How to query as GROUP BY in django?, How to use GROUP BY to concatenate strings in MySQL

Raz Hoshia
  • 106
  • 6
  • Thanks, you open my mind I was stuck trying to modify the CVS itself and never try modifying the model I use `SELECT id,model,name, group_concat(concat, ' | ') AS configurations_variatons FROM ( SELECT id,model,name, CASE WHEN color IS NULL THEN cod ELSE " cod=" || cod || "," || " color=" || color || "" END AS concat FROM products ) GROUP BY model` – Alejandro Hernandez Dec 21 '20 at 01:00