Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Import CSV Data Into Your Django Project

DZone's Guide to

Import CSV Data Into Your Django Project

·
Free Resource
// full context available at www.dunnreporter.com. 


import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')
   
for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]
                      
   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}