Pyton

How to Use bulk_create() in Django?

How to Use bulk_create() in Django?

Django framework can be used to create a web application with a database by writing script in models.py and views.py files of the Django app. The data can be inserted into the database tables by using Django Administration Dashboard or by writing a script in the views.py file. Django Administration Dashboard requires a login for an authenticated user to access the tables of the database. Single or multiple records can be inserted into the database tables by writing a script. bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create() method is used to insert the multiple data in a Django database table will be shown in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not

Setup a Django app:

Run the following command to create a Django app named bookapp.

$ python3 manage.py startapp bookapp

Run the following command to create the user to access the Django database. If you already created one, then you don't need to run the command.

$ python3 manage.py createsuperuser

Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [

'bookapp'
]

Create a folder named templates inside the bookapp folder and set the template's location of the app in the TEMPLATES part of the settings.py file.

TEMPLATES = [

… .
'DIRS': ['/home/fahmida/django_pro/bookapp/templates'],
… .
,
]

Create a model for the database table:

Open the models.py file from the bookapp folder and add the following script to define the structure of books tables. Book class is defined to create a table named books with title, author, price, and published_year fields. According to the script, title and author fields will store character data, and price and published_year fields will store the integer data. Here, the title field is defined with the unique attribute. That means that the value of the title field will not accept any duplicate data.

models.py

# Import models module
from django.db import models
# Define the Book class for the books table
class Book(models.Model):
title = models.CharField(max_length=100, unique=True)
author = models.CharField(max_length=100)
price = models.IntegerField()
published_year = models.IntegerField()

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations bookapp

Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the Book class of the models is registered using the register() method to display the books tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin
# Import Book model
from .models import Book
# Register Book model
admin.site.register(Book)

Create a template file named DisplayBookList.html inside the bookapp/templates/ folder with the following script. This script will display all data of books table in tabular form. Other than that, for loop is used in the script to iterate the data passed from the views.py file.

DisplayBookList.html



<br>Django bulk_create() Tutorial<br>



Python Book List







% for book in object_list %



% endfor %
IDNameAuthorPublication YearPrice
book.id book.title book.authorbook.published_year$book.price



Modify the content of the views.py file with the following script. The model and template names are defined in the BulkInsert class. get_queryset() method of the class is defined in the script to return all records of the books table. On the other hand, Book.objects.all() method is used to return all records of the books table. exists() method is used in the script to check the books table is empty or not. If this method returns False then five records will be inserted into the books table using the bulk_create() method.

views.py

from django.shortcuts import render
# Import ListView module
from django.views.generic import ListView
# Import Book model
from .models import Book
# Define class for inserting multiple data
class BulkInsert(ListView):
# Define model
model = Book
# Define template
template_name = 'DisplayBookList.html'
# Read all existing records of books table
queryset = Book.objects.all()
# Check the books table is empty or not
if queryset.exists() == False:
# Insert 5 records in the books table at a time
Book.objects.bulk_create([
Book(title='Python Crash Course, 2nd Edition', author='Eric Matthes', price=15, published_year=2019),
Book(title='Automate the Boring Stuff with Python, 2nd Edition', author='Al Sweigart', price=30,
published_year=2019),
Book(title='Learning Python', author='Mark Lutz', price=15, published_year=2019),
Book(title='Head First Python', author='Paul Barry', price=45, published_year=2016),
Book(title='A Byte of Python', author='Swaroop C H', price=15, published_year=2013),
])
# Return all records of the books table
def get_queryset(self):
# Set the default query set
return Book.objects.all()

Modify the content of the urls.py file with the following script. In the script, the 'admin/' path is defined to open the Django Administration Dashboard and the 'books/' path is defined to call the BulkInsert.as_view() method that will insert five records to the books table and return the records to the template file.

urls.py

# Import admin module
from django.contrib import admin
# Import path and include module
from django.urls import path
from bookapp import views
urlpatterns = [
# Define the path for admin
path('admin/', admin.site.urls),
path('books/', views.BulkInsert.as_view()),
]

Open the Django Administration Dashboard to check whether the data is inserted properly or not using the bulk_create() function.

The inserted records of the books table will be displayed in the browser after executing the following URL.

http://localhost:8000/books/

Conclusion:

Multiple records can be inserted into the Django database table in different ways using the bulk_create(). A simple way of inserting multiple records in the database table using this method was shown in this tutorial to help Django users understand the logic behind the process.

Gry Jak zwiększyć FPS w Linuksie??
Jak zwiększyć FPS w Linuksie??
FPS oznacza Klatki na sekundę. Zadaniem FPS jest pomiar liczby klatek na sekundę podczas odtwarzania wideo lub wydajności gier. W prostych słowach lic...
Gry Najlepsze gry w laboratorium aplikacji Oculus
Najlepsze gry w laboratorium aplikacji Oculus
Jeśli jesteś posiadaczem gogli Oculus, musisz wiedzieć o sideloadingu. Sideloading to proces instalowania w zestawie nagłownym treści innych niż sklep...
Gry Top 10 Games to Play on Ubuntu
Top 10 Games to Play on Ubuntu
Windows platform has been one of the dominating platforms for gaming because of the huge percentage of games that are developing today to natively sup...