Exporting items from a model to CSV Django / Python

前端 未结 9 2048
死守一世寂寞
死守一世寂寞 2021-02-03 09:52

I\'m fairly new to django and Python and want to be able to export a list of items in my model i.e products. I\'m looking at the documentation here - https://docs.djangoproject.

9条回答
  •  梦如初夏
    2021-02-03 10:28

    Using django.db.models.query.QuerySet.values results in more optimised queries for my use case.

    import csv
    from datetime import datetime
    
    from django.http import HttpResponse
    
    # Populate this list with your model's fields
    # Replace MODEL with your model
    fields = [f.name for f in MODEL._meta.fields]
    
    # The following code will live inside your view
    timestamp = datetime.now().isoformat()
    
    response = HttpResponse(content_type="text/csv")
    response[
        "Content-Disposition"
    ] = f"attachment; filename={timestamp}.csv"
    writer = csv.writer(response)
    
    # Write the header row
    writer.writerow(fields)
    
    # Replace MODEL with your model
    for row in MODEL.objects.values(*fields):
        writer.writerow([row[field] for field in fields])
    
    return response
    

提交回复
热议问题