Pages

Showing posts with label models. Show all posts
Showing posts with label models. Show all posts

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]
        tmp.save()

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