Importing CSV file into Django Database
This is a 5 steps guide to Import your data from a csv file to your django database using Django management Command.
A CSV is a comma-separated values file, which allows data to be saved in a tabular format.
Applications can register their own actions with manage.py
using custom django-admin
commands. For example, you might want to add a manage.py
action for a Django app that you’re distributing. In this article, we will import the data of children.csv to the children model using the custom django-admin
commands, such as:-
python manage.py load_child_data
children.csv:
Step 1- Make a Django Project named as csv_import.
django-admin startproject csv_import
Step 2- Make a Django app named as children.
python manage.py startapp children
Step 3- Now, we will make a model to store the data of the csv file and register that model in Django admin interface.
models.py:-
from django.db import modelsclass children(models.Model): name=models.CharField(max_length=100)
SEX_CHOICES=[('M','Male'),('F','Female')]
sex = models.CharField(max_length=1, choices=SEX_CHOICES)
age=models.IntegerField(null=True)
def __str__(self):
return self.name
admin.py:-
from django.contrib import adminfrom .models import children@admin.register(children)class childrenAdmin(admin.ModelAdmin): list_display=['name','sex','age']
Note: Make sure you have added our app in installed apps in settings.py, migrated all the migrations and created a superuser to see the data in the database.
Step 4:- Now, we will add a management/commands
directory to the application. Django will register a manage.py
command for each Python module in that directory whose name doesn’t begin with an underscore. For example:
children/
__init__.py
models.py
management/
commands/
_private.py
load_child_data.py
tests.py
views.py
load_child_data.py:-
Step 5:- Finally, paste the CSV file i.e., children.csv in the same folder as manage.py
and type in the command prompt or shell:
python manage.py load_child_data
Run the server.
Wooohoooo! Check the database to see the loaded data from the CSV file into your django model.
In case you still have any doubts you are welcome to refer to my github repository for the same by the following link:-
Hope this helps!