Dec. 25, 2017, 12:16 p.m.
Django documentation suggests pre-populating a database using fixtures (which support data importation from xml, json, and yaml files) but I wanted to populate the database directly from a CSV file. I used the RunScript command from django-extensions. Here's how I did it:
import sys, os, django, csv
csv_filepath_name = "/Users/norafergany/djangoproject/file.csv"
djangoproj_home = "/Users/norafergany/djangoproject"
from app.models import Model
with open(csv_filepath_name) as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
_, created = Model.objects.get_or_create(
The script iterates through the file and treats each row as a unique model object, assigning each cell's value to the proper model attribute. To run the script, go into your Django project home in the terminal and run the following command:
python3 manage.py runscript script_name
If the script successfully executes, the model objects will print to the terminal.