This post covers the simplest way to import a .CSV file into a Django model.
I have created an app in Django – with news, and the companies mentioned in those news. The idea is that when a user adds a news as a new entry, s/he can also mention, the countries present in that news. E.g. If there is a news that ‘US and UK sign a bilateral deal, ‘ then the user can add the countries — US and UK while adding that news into the model.
The model.py file is straightforward:
class Country(models.Model): country = models.CharField(max_length=100) continent = models.CharField(max_length=100) class Meta: ordering = ('country',) # helps in alphabetical listing. Sould be a tuple def __str__(self): return self.country+" : "+self.continent class News(models.Model): news_title = models.CharField(max_length=200) news_link = models.CharField(max_length=100) news_date = models.DateField() news_country = models.ManyToManyField(Country) def __str__(self): return self.news_title
Now, in the Country model, I had to enter all the countries, and their continents. One way is to go to the admin panel, and start adding each country — one at a time.
A much easier way is to get all the countries into a CSV file, and then import the CSV file at once. I googled and found a site with countries, their capitals, and their continents. I copied the countries and continents as a CSV, by adding the column name as the top row.
Country,Continent Afghanistan,Asia Albania,Europe Algeria,Africa Andorra,Europe Angola,Africa Argentina,South America Armenia,Asia
Once, I had the CSV ready, went to the Django Shell, using python manage.py shell, and imported the CSV using following code:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import csv >>> import os >>> path = "C:\\...." # Set path of new directory here >>> os.chdir(path) # changes the directory >>> from dashboard.models import Country # imports the model >>> with open('countries_continents.csv') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in reader: ... p = Country(country=row['Country'], continent=row['Continent']) ... p.save() ... >>> >>> exit()
That’s it. The CSV has been imported,
Running python manage.py runserver and checking the Countries class in the admin module, gave the list of all the countries and their continents.