Django: Add Data to Database Step-by-Step
To add data to the database in Django, you can use Django’s models and managers to manipulate the database. Here are the general steps to add data to the database:
Create a model class: To begin with, a model class needs to be created in the models.py file of the Django application to represent the data to be added. For example, if a book record named “Book” is to be added, a model class can be created as follows:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publish_date = models.DateField()
Option 1:
Migrate the database: After defining the model classes, you need to run the following command to create or apply database migrations.
python manage.py makemigrations
python manage.py migrate
3. Adding data: You can use objects of model classes in the Django shell to add data. Run the following command to open the Django shell:
python manage.py shell
Next, use the following code to add a record of a Book to the database:
from myapp.models import Book
book = Book(title='Django for Beginners', author='Jane Doe', publish_date='2022-01-01')
book.save()
The data should now have been added to the database by saving it through the save() method of the model class. There should now be a new book record in the database with the name “Django for Beginners”.
The above are simple steps to add data to a database in Django. By using model classes and managers, it is easy to manipulate the database and add, update, or delete data.