Tuesday, June 25, 2013

A Django Management Command to Load CSV Data Into a Database Table




This code expects input data that looks like this:

First,Last,Age,Sex
John,Smith,26,Male
Jane,Doe,34,Female
              .
              .
              .

Assuming no irregular data, this sure is easy:

from django.core.management.base import BaseCommand, CommandError
from app.models import Profile
import csv

class Command(BaseCommand):
   def handle(self, *args, **options):
       self.stdout.write(args[0])

       with open(args[0], 'rb') as file:
           rows = csv.reader(file, delimiter=",", quotechar='"')

           for row in rows:

              if rows.line_num == 1:
                 continue

              row[3] = row[3].replace("\n", " ")

              print "First: " + row[0]
              print "Last:  " + row[1]
              print "Age:   " + row[2]
              print "Sex:   " + row[3]

              db_row = Profile(first=row[0], last=row[1], age=row[2], sex=row[3])
              db_row.save()

           # dump entire table
           for person in Profile.objects.all():
              print person


5 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete