Nora Fergany


Posts for: Python

Populate a Django Database with a Script

Dec. 25, 2017, 12:16 p.m.

It took me quite some time to figure out how to pre-populate a Django database from a csv file. Django documents suggest using fixtures, but I wanted to populate the database directly from my file. I used the RunScript command from django-extensions (https://django-extensions.readthedocs.io/en/latest/runscript.html) , which allows you to run a set of commands in shell accessed by python manage.py shell. Here’s how I did it:



import sys, os, django, csv
csv_filepath_name = "/Users/norafergany/djangoproject/file.csv"
djangoproj_home = "/Users/norafergany/djangoproject"

sys.path.append(djangoproj_home)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject.settings")
django.setup()
from app.models import Model


def run():
with open(csv_filepath_name) as f:
reader = csv.reader(f, delimiter=',')
next(reader, None)
for row in reader:
print(repr(row))
if row:
_, created = Model.objects.get_or_create(
model_attr1=row[0],
model_attr2=row[1],
model_attr3=row[2],
)


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.