Python and Django Full Stack - Using Django models to communicate with PostgreSQL Database

Django – Using Models to communicate with PostgreSQL Database

So far we have learnt to set up our project and its applications, create views and map URL, using simple templates and tags, and serving media files.
 
Now, we will learn about Django models and how to use them to communicate with the postgreSQL database. We will also learn about the Django admin interface.

1.1.  Settings to connect to PostgreSQL

Django comes with an inbuilt sqllite3 database. In the project's settings.py file, there is a section on DATABASES which by default points to the sqllite3 database.

To ask Django to connect to PostgreSQL, change the 'default' DATABASES dictionary in the Django project's settings.py file, like so:

 DATABASES = {

'default': {
       'ENGINE': 'django.db.backends.postgresql',
       'NAME': 'fooddb',
       'USER': 'xxxxx',
       'PASSWORD': 'xxxxx',
       'HOST': 'localhost',  # or your database server's IP address
       'PORT': '5432',  # or your database server's port number
       'OPTIONS': {
                'options': '-c search_path=foodschm'
                }
    }
}

If your schema is different from the default public schema, then use the OPTIONS keyword.

In the OPTIONS dictionary, add a key options with the value of -c search_path=your_schema_name, where your_schema_name is the name of the schema you want to use. This will set the default schema to use for all queries made through Django.

You can also specify the schema name in your models, by adding the Meta class to your model and setting the db_table attribute. This is explained in the following section.

1.2 Django Models

Models are used to send instructions to the database and can be thought of as being similar to commit queuing and actual commit.

1. In the project folder, open the models.py file, and include the following data definition for  the model. Note that you can use the name “id” for a column only if it is also the primary  key.

from django.db import models

# Create your models here.
class menu(models.Model):
    id = models.CharField(max_length = 5, primary_key=True)
    name = models.CharField(max_length=15)
    description = models.CharField(max_length = 30)
    price = models.DecimalField(max_digits=5, decimal_places=2)

    def __str(self):
        return self.id
Define your schema here, if diffferent from the default public schema
class Meta:
      db_table = 'your_schema_name.your_model_table_name'

In the db_table attribute, add the name of the schema and the name of the table you want to use for this model. This will tell Django to use the specified schema and table for all queries made for this model.

2. Now register these changes. From the Project terminal,
Command Prompt > python manage.py makemigrations
 
3. Next,
Command Prompt> python manage.py migrate

Now, to confirm all this worked, and that the columns were actually created/updated in the database, we test it by inserting data into the database and querying it back. We will do this using Python's interactive Shell. Note that just a little time later, we will be looking at the Django's admin feature which will help us perform these activities much more easily.

1.2. Inserting data into database using python Shell

1. From the project folder, open interactive python shell
 Command Prompt > manage.py shell

     2. Next, at the interactive shell command prompt,

In[1]: from backendapp.models import menu
In[2]: print(menu.objects.all())
<QuerySet[] >

 
        This will return an empty dataset because there are no records in the database. 
 
      3. Add a record to the database.
        
ln [3]: t = menu(id = 'm1', name = 'Sushi', description = 'Finest fish and  veggies',
price = 22.99)
In [4]: t.save()
In [5]: print(menu.objects.all())
<QuerySet [<menu: menu object (m1)>]>


It returns ‘m1’ because we asked it to return id in the model. 
 
4. Quit the shell.
 In [6]: quit()

         We have now confirmed that the model is working fine. We will now look at the Django Admin interface.

1.3.   Django Admin Interface.

In order to have a more interactive experience with the database, you can use the Admin interface. This section describes how.

1. Register the models to the application through the project’s admin.py file. 

      From the backend models file, import the required models and register the model with the app using the admin.site.register(model)

from django.contrib import admin
from backendapp.models import menu
# Register your models here.
admin.site.register(menu)

 
2. Create a super user for security.

    From the project terminal,
Command prompt> manage.py createsuperuser
 
    This command will ask you to enter the username, email id and password you want to use when Django connects to the database.

Username(leave blank to use 'xxxxx'): xxxxx
Email address: xxxxx@xxxx.com
Password:
Password(again):
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.


 Be sure to note this down somewhere. If you lose it, you will have to go through the entire process again.
 
3. Now run the server from the project folder and check out the admin interface in the browser.
Command prompt> manage.py runserver

4. Redirect to 127.0.0.1:8000/admin and open the page. This will open up the Django admin interface screen asking for a username and password. Enter the username and password you just created.


     5. Log into the screen and you will see the Django administration interface.


6. Click on 'menus' and you will see the menu items you created.



On this screen, you can add menu items, delete menu items, select individual menu items to edit them, thus making it very easy to manipulate data directly.

In the next post, we will see how to query from the reactjs front end and present this data. 

Comments

Popular posts from this blog

Python and PostgreSQL – Creating database, schema, tables and inserting data using python library psycopg2

Full Stack Web Developer BootCamp. (A course by Jose Portilla on Udemy) - Updated for recent versions of Python and Django

Python and Django Full Stack - Have React speak to PostgreSQL