Tagged: Back end, Django, PostgreSQL, SQLite, Web framework
- This topic has 1 reply, 2 voices, and was last updated 1 year, 5 months ago by
.
- AuthorPosts
- February 22, 2020 at 8:54 pm #86493Spectator@idowu
Recently, I put up an article on how to customize the Django default homepage. In that article, I explained how to access the admin page of the SQLite database that comes with the Django framework. SQLite is a light-weight database (which might not be amenable to the typical future expansion of an application). It then becomes necessary in most cases to replace it with a proper database – this is so that we can have a more scalable database that can accommodate as much as we want in the future – preferably, one which is supported by the cloud.
There are several database management engines, some of which include Oracle, MongoDB, PostgreSQL, and MySQL. In this tutorial, we’ll be replacing the default SQLite database of Django with the PostgreSQL database engine.
PostgreSQL is a highly scalable and sophisticated open-source relational database management engine that supports both relational and non-relational querying.
Object migration to the database in Django uses the concept of Object Relational Mapping (ORM) – which is a process of mapping created objects (from models.py) with tables on the database. In essence, the concept of ORM allows a user to interact with the database via an application.
Assume that you intend to build an e-commerce application. By convention, you’ll like to have a table that contains the details of your products and another that contains your customers’ details. Each of these tables (product_details and customer_details) will be managed by a single database that is connected to your application. Tables will be made by creating two classes in your models.py file. Each class represents an object (product_details and customer_details), each with its unique fields or states (the columns that you want each of the objects to contain).
However, for users to interact with the objects on a database, SQL queries that allow users to do so without admin access are involved. The automatic creation of these interactive queries is handled with the Model, Views, Templates method of Django framework.
Setting-up PostgreSQL and PgAdmin
To link your app with PostgreSQL, you’ll need to start by downloading the application file from the PostgreSQL website. On the download page, select your operating system and click on Download the installer.
Once you have the PostgreSQL downloaded, launch the file to install it on your machine.
During the installation, you’ll be prompted at some point to set-up a password for the PostgreSQL database. This password will be used as an access Id whenever you launch the engine.
To successfully launch the PostgreSQL engine, we’ll need a user interface that will allow us to access the database. For that, we’ll have to download and install the Pgadmin (ensure that you select the right operating system).
Once you get the two set-ups ready, you can launch the PostgreSQL engine by opening pgAdmin. The password that was set-up earlier will be requested, provide that. Once the Pgadmin is opened on your browser, it creates an interface for viewing the items in the PostgreSQL database. Looking at the top left-hand corner of your screen, you’ll see the servers – this contains a list of stuff like views and tables that have been created by default already.
Open up your Django project in sublime text or any IDE of your choice. Use python manage.py startapp app_name in your command line to start an app within your Django project folder and add it to the list of INSTALLED APPS in settings.py.
The next action will be to connect your app to the database. We’ll first have to logon to pgAdmin and create a database (you practically don’t need to write any query). In pgAdmin, click on servers. Once that panel opens, right-click on the pre-existing database and click on create to create a database. Give the database a name (this can have the same name as your app). This new database will now hold the objects we’ll be creating in our app.
If all these are strange to you, check out my introductory article to Django.
Although we’ve created a database, this database is not yet linked to our app. To do that, we’ll be making some changes to the list of databases in settings.py by changing the default connected database to PostgreSQL.
Make the following changes to the list of DATABASES in settings.py:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_app', 'USER':'postgres', 'PASSWORD': 'idowu', 'HOST':'localhost' } }
We’ve now replaced the engine with PostgreSQL. To connect successfully to our new database – we stated the name of our app and we also specified that the user is Postgres (remember that this was given by default during PostgreSQL installation). The password will be the one you gave during installation, while the host is localhost.
However, Python will not connect with the PostgreSQL without an adapter. The most popular and easy to use database adapter for PostgreSQL and Python is psycopg2. To install this adapter – on the command line, run
pip install psycopg2
. Once the adapter is installed, we can be certain that both Python and PostgreSQL will be connected.To see if our connection worked, we’ll create a model and make migrations into the PostgreSQL database. The model will be created inside the models.py file by using the class method to define the object (table) we intend to create.
We’ll be creating a table that contains product information. In that object, we’ll be storing the following states (fields or columns):
- Product name
- Product details
- Price
- Product image
from django.db import models # Create your models here. class product_info(models.Model): Product_name = models.CharField(max_length = 70) Product_description = models.TextField(max_length = 300) Price = models.IntegerField() product_image = models.ImageField(upload_to='images')
Creating the class product_info implies that the object on the database will inherit that name (product_info). It is appropriate to store names with the CharField since names can sometimes contain characters other than letters or strings. TextField will only save data in the form of texts and the Max_length can also be set for each field (as seen above).
To store images on the database, we used the ImageField – the upload_to function will ensure that uploaded images are stored in a particular folder within our project (you can create this folder in the file explorer). However, to make image migrations to the database, we need to install an image management library called pillow by using
pip install pillow
command on the command line (ensure that you’re still in the virtual environment).Once the above step is done, we can now make migration files by running
python manage.py makemigration
on the command line.When you check the file explorer, you’ll see a folder named migrations – this is where all the migration files are stored. Within that folder, click on the file named 0001_initial.py.
By default, the product_id field is created and set at auto_increment when we created our model.
By now, we would expect that all our objects are already migrated to the database – this is not true. We still need to specifically migrate into the PostgreSQL database. To do that, we will use python manage.py sqlmigrate app_name 0001. The actual migration is then made by running
python manage.py migrate
command.We’ve simply instructed python to migrate the models we created in our app into the PostgreSQL database. Future changes to that particular object class will simply be handled with the python manage.py migrate command.
To view the object on the database, let’s open up the pgAdmin once more. In the pgAdmin, right-click on the database that was created earlier and click on refresh. Expand the schemas panel and check for the tables.
Like I stated earlier, the table inherits the name of the class (product-info) we created in the model.
To view the fields on the table, simply right-click on the product_info table. Click on view data, then select all rows.
Summary
We’ve been able to replace the default SQLite database with the PostgreSQL database in Django. The basic concepts of creating an object class in the models.py files were also considered. Finally, we were able to create migration files and migrate specifically into the PostgreSQL database.
December 13, 2020 at 7:59 am #94226Spectator@opereztThanks a lot by your article has been very useful. Greetings from Peru
- AuthorPosts
- You must be logged in to reply to this topic.