Friday, October 18, 2013

Importing CSV file into django model.

Lets assume that we have the following django model:
class Person(models.Model):
    PersonID = models.CharField(max_length=10)
    FirstName = models.CharField(max_length=30)
    LastName = models.CharField(max_length=30)
    Address = models.CharField(max_length=30)

and we have a csv file with 4 elements on each row and we want to import them in our django database. Here is example (delimeter is !):
1!Nikolay!Hristov!Bulgaria, Gabrovo, Test street 18 
What we need to do is to make a view and attach it to certain url (for example http://localhost/import_db/). Here is the view:
def import_db(request):
    f = open('/path/to/filename-with-data.csv', 'r'
    for line in f:
        line =  line.split('!')
        tmp = Person.objects.create()
        tmp.PersonID = line[0]
        tmp.FirstName = line[1]
        tmp.LastName = line[2]
        tmp.Address = line[3]

Now all we have to do is to point our browser to http://localhost/import_db/ and wait for data to be imported.


cacko said...

import_db бих го написал примерно...без много да се замислям

може и да не работи това де, не съм го тествал, но идеята е видна.

Anonymous said...

great work.
However it didn`t work if you have foreign key in your csv file.

Anonymous said...

thank you!

Anonymous said...

thanks you the code helped me a lot :)

TryingtobeAhmad said...

Great Work all the way from the middle east. I used your code and it helped me a lot with my bladder cancer research !!!

Anonymous said...

nice really helped me

Vaidehi Khavnekar said...

thank you so much it worked