Code that doesn’t suck

Once in a while I manage to belt out a bit of code that doesn’t suck. This is a post with one example. I have a csv file with a bunch of rows of data that need to be added to a database. I’m using the django python framework to develop a web front-end for the database, so using django to add bulk data from a csv file seemed like a good idea too. Here is some code:

def buildModel( model, row ):
# constuct an instance of the model
m = model()

# get a list of the fields in the model
fieldList = [ for f in m._meta.fields ]

# add data to the fields
for i, fieldName in enumerate( fieldList ):
setattr( m, fieldName, row[i] )

return m

def loadData( fileName, appName, modelName ):
import csv
from django.db.models import get_model

# fetch the relevant model
model = get_model( appName, modelName )

# open file using csv module
csvReader = csv.reader( open( fileName ) )

# loop over every line in the csv file
for row in csvReader:
# create a model object using the data in row
o = buildModel( model, row )

# save company

The loadData() method processes the csv file row by row. buildModel() takes advantage of the direct correspondence between the order of items in the row with the fields of the django model. The returned model is then save()’d to the database.

Nothing special, just worked out small and neat.


  1. admin says:

    Wow, the formatting in this blog post sure does suck. You’ll have to imagine the ‘code’ tag actually does something.

  2. Danno says:

    Cool! Meanwhile I came across this gem by Microsoft: the only default event available for a scrollbar is for when you change your Windows theme.

    Choice quote:
    “I might have avoided the problem had MS been rash enough to add ON_WM_VSCROLL as an option for “Add Event Handler”. Did it not dawn on them that someone might actually want to be able to handle the scrolling of a scroll bar? “

Leave a Reply