Django Framework with Database
In this tutorial, we are going to explain the how to connect the Django Framework with a database, such as - Oracle Database 18c Express Edition Release 18.0.0.0.0.
If you are trying to connect Django Framework with Oracle database, then you need to install the cx_Oracle package.
Softwares required before we install cx_Oracle
To connect Python with Oracle database using cx_Oracle, we need the have the following software packages installed in our system:
- You must have installed Django(we have Django 2.2.2 version).
- You must have installed Python(we have Python 3.7.3 version).
- You must have installed an Oracle database(we have Oracle Database 18c Express Edition Release 18.0.0.0.0)
Note: Please make sure to follow the links of the above software packages to install the correct and the latest version(at the time of writing this tutorial)of each software. An older version of any of these software may not work the new version of the other mentioned software.
Once we have installed all the above mentioned software packages, we need to move to the next step i.e. installing the cx_Oracle module.
Installing cx_Oracle package
The cx_Oracle is a module which acts as a communication channel between Python API and Oracle database.
To install the cx_Oracle, you need to open the command prompt and move to the directory where the pip.exe is present on your system.
Once you've correctly installed the Python languages, the directory of pip.exe is - "C:\Users\User_Name\AppData\Local\Programs\Python\Python37\Scripts"
Move to the above mentioned directory and enter the following command:
pip install cx_Oracle
This installs the cx_Oracle in our system.
And that's it! We have installed all the important software packages needed to connect Django Framework with Oracle database using Python language. In the next tutorial, we are going to teach you about how to connect a Django project with Oracle database using Python. So, please turn over the page.
Creating a Django Project
So let us create a Django project to explain you how to work with the Django Framework in connection with a database. For those who have not read our last tutorials and for those who don't know how to create a Django project, here is a recap.
Creating a Django project
To create a directory for our project, we need to open the Command Prompt and type in the command -
django-admin startproject django_db2
- dhago-admin is a management utility for Django Framework, using which we could create a new project and much more.
- startproject is a command to start a new Django project.
- django_db2 is the name of our Django project and also the name of our project directory created in the current directory.
The startproject command gives us a sub-directory and files
Executing the startproject command has not only created a project directory named django_db2, but has also created a file manage.py and another sub-directory with the same name as the project directory, which also contains some Python files -
django_db2/
manage.py
django_db2/
__init__.py
settings.py
urls.py
wsgi.py
- django_db2 is the root directory of our Django project, also known as the container of our project.
- manage.py is a command-line utility which allows us to interact with Django project in various ways.
- django_db2 sub-directory is actually a Python package for our project. We can import this package(a group of modules) and its contents just like we import any general Python package/module and its contents.
- __init__.py is a file which allows our sub-directory django_proj1 to be treated as a Python package.
- settings.py is a file used for setting the configurations for our Django project.
- urls.py is a file used to specify the URL declarations for our Django project, also known as a a table of contents.
- wsgi.py is a file used as an entry-point for WSGI web-servers to serve your project.
Starting the development server
After creating the project directory and the files required to run our Django project, it is time to execute the Django Development Server. To do this, we will have to open the command prompt, change the current directory to the root directory of our Django project and execute the following command.
python manage.py runserver
Executing the above mentioned command will trigger the Django Development Server in action, as you can see in the picture below.
Now that you have successfully started the Django development server, it is time to visit the http://127.0.0.1:8000/ link and you will see a webpage displaying a congratulatory message, as shown below.
Note: The runserver command runs the Django development server at the port 8000.
Creating an app in our project
A project may contain one or multiple applications. As we have already created a project, now let us create a welcome application in it which welcomes the user. This application will be created right under our root - project directory django_db2.
To create an application, we have to open another window command prompt, change the current directory to the root directory of our Django project and execute the following command -
python manage.py startapp customer
The command startapp in combination with manage.py utility is used to create an app of a project, using which we have created an app named - customer.
Executing the startapp command has not only created an application directory named customer in the root - project directory, but has also created the following set of Python files -
customer/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
migrations/
__init__.py
Creating a model.py file for our app.
Next, we have to create a model class, where each model class corresponds to a database table on which we could perform database operations by using the Django Framework. Each model class is a subclass of django.db.model.Model class.
Note: The upcoming model class - Customer_Info is defined in the file models.py, which is already created and stored in our application directory, customer. Let us just copy and paste the following code in models.py.
models.py
from django.db import models
# Creating our model class - Customer_Info
class Customer_Info(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=30)
state = models.CharField(max_length=50)
country = models.CharField(max_length=30)
def __str__(self):
return (self.name + ', ' + self.address + ', ' + self.city + ', ' + self.state + ', ' + self.country)
Each model class could have a number of class variables, where each class variable represents a database field in the database table.
Each database field is represented by an appropriate Field class, such as -
- CharField class is used to specify character fields
- DataTimeField class is used to specify the datetimes field.
- URLField class is used to specify a URL field.
The name of the field is used a column name in the database table.
As you can see in the model class Customer_Info, we have defined its class variables such as name, address, city, state, country using the appropriate Field classes, where each of these class variables correspond to a column name in the database table.
Note: Django automatically gives an integer primary key field called id to each model class.
Installing the Model
Next, we need to add the app customer to our project by adding the reference to its configuration class in the INSTALLED_APPS property within the settings.py file(which is present within the django_db2 folder).
The CustomerConfig configuration class named CustomerConfig is present in the apps.py file within the app customer folder.
Within the settings.py file, you need to locate the property INSTALLED_APPS and copy-paste the full-path of this configuration file against it, as shown below and save the file.
INSTALLED_APPS = [
'customer.apps.CustomerConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Now Django Framework will include the customer app on executing this Django project.
Storing the migrations
Next, we need to execute the makemigrations command to tell Django Framework that we have made some changes to the existing models or have specified new models and in our case, we have specified a new model class in our app Customer.
- We can execute the makemigrations command from within the project directory in combination with the manage.py file, as shown below.
python manage.py makemigrations customer
Note: Migrations are just files specifying the changes to the existing models or when we specify new models.
Specifying the database configuration
Next, we need to specify the database configurations within the settings.py file(which is present within the django_db2 folder). These database configurations tells Django which database we are going to use and how to connect it. The database configurations settings could be different depending on the database you are using to connect to using the Django Framework.
Note: The upcoming database configurations are specific to Oracle Database.
Within the settings.py file, you need to locate the property DATABASES and specify the database configurations against each database setting such as engine, name, user, password, host, port, as shown below. Save the file once you've specified the database configurations.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'XE',
'USER': 'System',
'PASSWORD': 'Tiger',
'HOST': 'Scott',
'PORT': '1521',
}
}
While specifying the database setting, such as - password and host, please enter your Oracle's database password and username. Now, using these database configurations, the Django Framework will be able to connect to the Oracle Database.
Executing the "sqlmigrate" command
If you want to see the SQL statements required to implement the migrations that we have stored, then please execute the sqlmigrate command, as shown below.
python manage.py sqlmigrate customer 0001
The sqlmigrate command should be executed with manage.py, followed by the name of the app, which in our case is customer, followed by the name the migration file that we have just created, which in our case is 0001, and it returns its equivalent SQL commands, which is displayed in the picture below.
Please Note:
- The sqlmigrate command does not execute any SQL statement and no database table is created after executing this command, it only shows us the SQL statements required to implement our stored migrations. To execute these SQL statements, we need to execute the migrate command.
- As you can see from the SQL statements in the picture above, a table Customer_Customer_Info will be created i.e. name of the app combined with an underscore(_) and name of the model class specified in the models.py file.
Executing the "migrate" command
So far, we have only stored the database migrations and have seen the SQL statements required to implement the migrations in a database. Now let's execute these SQL statements to implement the migrations and apply the changes to the database by using the migrate command, as shown below.
python manage.py migrate
The migrate command should be executed with manage.py and it applies the stored migrations(as shown below) and creates the necessary database tables corresponding to the model classes specified the file, models.py.
On executing the migrate command, a new database table customer_customer_info is created, which you can verify by entering the following SQL command at the SQL prompt in SQL PlUS:
SQL> select * from customer_customer_info;
no rows selected
SQL>
Inserting the data into database
Once we have created a database table, we can simply insert a row of data in this table by executing a few commands in Python. To do this, first we have to execute the following command at the command prompt which opens the Python shell, with a prompt >>>.
python manage.py shell
At Python Shell, we are going to enter a few Python statements to insert the data in this database table, as shown below. We are first going to import our model class Customer_Info, create its object and save it.
E:\Django Project2\django_db2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from customer.models import Customer_Info
>>> cust1 = Customer_Info(name='Shawn', address='271 N Monroe St', city='Tallaha
ssee', state='Florida', country='USA')
>>> cust1.save()
>>> customer_info_list = Customer_Info.objects.all()
>>> customer_info_list
<QuerySet [<Customer_Info: Shawn, 271 N Monroe St, Tallahassee, Florida, USA>]>
>>>
Program Analysis:
from customer.models import Customer_Info
cust1 = Customer_Info(name='Shawn', address='271 N Monroe St', city='Tallahassee', state='Florida', country='USA')
cust1.save()
customer_info_list = Customer_Info.objects.all()
customer_info_list
Displaying the saved object using SQL PLUS
Additionally, you could even run the SQL PLUS to see the content of the database table that we have just created and inserted data into, by entering the following SQL command at the SQL prompt:
SQL> select * from customer_customer_info;
ID NAME ADDRESS CITY STATE COUNTRY
---------- ---------- ------------ ---------- ---------- -------------
23 Shawn 271 N Monroe Tallahasse Florida USA
No comments:
Post a Comment