Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a script that uses a .csv file into insert data to the Django model. Now, I wonder if there's a better way of doing this.

with open('some/path/to/file.csv') as f:
  reader = csv.reader(f, delimiter=',')
  header = reader.next()
  for row in reader:
    Foo.objects.create(first_name=row[0], last_name=row[1])

That's basically what it does. I just wonder if it can be refactored somehow.

share|improve this question

migrated from stackoverflow.com Nov 17 '13 at 5:36

This question came from our site for professional and enthusiast programmers.

3  
When you have it down to 10 lines or less worry less about refactoring. Enjoy the win. –  Back2Basics Nov 9 '13 at 6:52
    
Thanks you so much! –  Boy Pasmo Nov 9 '13 at 6:55
add comment

1 Answer

up vote 3 down vote accepted

If you are using Django 1.4+, you can use bulk_create method.

And I would rather use next function instead of next method because function version works both in Python 2.6+ and Python 3.x. (iterator.next is renamed to iterator.__next__ in Python 3.x).

with open('some/path/to/file.csv') as f:
    reader = csv.reader(f, delimiter=',')
    header = next(reader)
    Foo.objects.bulk_create([Foo(first_name=row[0], last_name=row[1]) for row in reader])
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.