I’m seeking assistance in exporting data from a Django model to a CSV file using the csv module in Python. I’ve read about the process, but I’m struggling to put together the necessary code within my Django project. Could someone kindly provide a code example or guide me through the process?
Here’s the simplified version of my Django model:
# models.py
from django.db import models
class Product(models.Model):
ProductID = models.IntegerField()
ProductName = models.CharField(max_length=100)
Price = models.DecimalField(max_digits=10, decimal_places=2)
I want to export the data from the Product model to a CSV file named products.csv . How can I achieve this using the csv module along with Django’s ORM? I read various articles and post but haven’t got any solution, I’d greatly appreciate it if someone could provide a code snippet or step-by-step explanation to help me get this CSV export functionality up and running within my Django project. Thank you for your assistance!
If you want to download the csv file in the browser, you can try to pass your model to the client (Via jsonResponse if API request or via context for view rendering)
Then you cant treat this data with a js script CLIENT SIDE and trigger download.
I just did something similar and here is my client side js to trigger the download if you want to get some inspiration
function generateAndDownloadCsv(){
// Convert JSON to CSV
let csvContent = "";
jsonData.forEach(line => {
line = line.join(";").replace(/(\r\n|\n|\r)/gm, "")
csvContent += line + "\n"
});
// Create a Blob with the CSV content
const csvBlob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
// Create a URL for the Blob and set up download link
const downloadLink = document.createElement("a");
downloadLink.href = URL.createObjectURL(csvBlob);
downloadLink.download = "data.csv";
downloadLink.style.display = "none";
// Append the download link to the body and click it to trigger download
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
jsonData is my raw data i want to put as a csv, you can adapt this to your model. You get the idea.
you can trigger this function when you get your API’s responses for example