Saving Your Django Models Data into CSV File

Mohd Mujtaba
3 min readJun 21, 2022

When you are working in an early age startup company, most of the features are yet to be built and reports are among one of them.

In this article we’ll talk about how we can save database records into a CSV file with the help of our Django models and it will be divided into two parts.

In the first part we’ll talk about how to fetch data from database tables using Django and in the second part we’ll be writing the data into CSV file.

So let’s get started.

Let’s decode the code.

So here our main function is write_db_into_csv which takes a list of table names as input [Optional].

model_list = apps.get_models()
This line will fetch all the models that is registered under Django Apps inside settings.py file.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

for django_field in model._meta.get_fields():
This line basically fetches all the columns [fields] that are present in that particular table and storing the column name in columns list, which later we’ll use as headers for our CSV.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

Hence, in the last line of our part1 we are checking if we’ve provided any specific model name as input else it will write all the table data into the CSV.

Let’s move to the 2nd part of the blog.

In the function write_in_csv_table_wise we’ll be passing our model instance and the headers of that model. Let’s understand the working of each line.

table_name = model.__name__
print(f”started writing {table_name} table data into csv file”) print(“Current working directory”,os.getcwd())
This code will basically print the current working directory where the CSV file will be created and the table name.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

with open(f”{table_name}.csv”,’w’,newline=’’) as file:
writer = DictWriter(file,fieldnames=columns)
writer.writeheader()
Opened the file with file name as table name and written the header into the file.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
values = model.objects.all()
Get all the record of that model/table
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
for val in values:
row_data = [str(getattr(val,column,None)) for column in columns]
writer.writerow(dict(zip(columns,row_data)))

In the above line we are fetching a single row data from model instance and putting it into a list.
Finally writing the row into the CSV.

Thank You for reading till here.
You can find full code on my github profile
https://github.com/iammujtaba/django_related_stuffs/blob/master/save_db_into_csv.py
And can follow me on LinkedIn
https://www.linkedin.com/in/mohdmujtaba/

--

--

Mohd Mujtaba

SDE-2 @ Wealthy.in | Built systems from scratch | Exploring new Technology