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 18What 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):Now all we have to do is to point our browser to http://localhost/import_db/ and wait for data to be imported.
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()
7 comments:
import_db бих го написал примерно...без много да се замислям
http://pastebin.com/VKqdSnhe
може и да не работи това де, не съм го тествал, но идеята е видна.
great work.
However it didn`t work if you have foreign key in your csv file.
thank you!
thanks you the code helped me a lot :)
Great Work all the way from the middle east. I used your code and it helped me a lot with my bladder cancer research !!!
nice really helped me
thank you so much it worked
Post a Comment