
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Importing data into models in Django
In this article, we are going to see how to import data from json format to model. We can import data from json, csv, xlsx, yml, etc. to model.
First of all, create a Django project and an app. Set up urls and do some basic stuff like adding the app in INSTALLED_APPS.
Create a model. Here, we don't have much to do with views.py, urls.py or any html file. We only have to work with settings.py, admin.py, models.py and admin urlpoint.
Example
Install the django-import-export package −
pip install django-import-export
In settings.py, add the following line −
INSTALLED_APPS += ['import_export']
It will add import_export as an app in our project.
Create a model −
class StudentData(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100)
We created the model for testing and trying.
In admin.py −
from django.contrib import admin from .models import StudentData from import_export import resources from import_export.admin import ImportExportModelAdmin class StudentResource(resources.ModelResource): class Meta: model = StudentData class StudentAdmin(ImportExportModelAdmin): resource_class = StudentResource admin.site.register(StudentData,StudentAdmin)
Here we created a model resource for import and export. Then, we created an admin and registered it.
File format for JSON should be like this −
[ { "id": 13, "name": "John", "standard":"10", "section": "B", "the_json": {"name":"Jhon"} } ]
Field name as key and its value. On Notepad, make a file and save it with the name import_example.json.
Output
Now just import the JSON file import_example.json and your data will be imported in Django model.
- Related Articles
- Exporting models data in Django
- Implementing models reversion in Django
- Adding JSON field in Django models
- Making a Pickle field in Django models
- Importing Data in Python
- Django – Showing model data directly into table with sorting and pagination
- Object based Data Models
- Evolution of Data Models
- Django model data to JSON data in 2 lines
- Importing data from Pgsql to SAP HANA database
- History of Data Models and Databases
- Table type while importing data from flat file in SAP HANA
- Different mapping options in SAP HANA while importing data from flat file
- What are the types of data mining models?
- Importing External Style Sheets in CSS
