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.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:
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 schemaclass 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.
1.2. Inserting data into database using python Shell
1. From the project folder, open interactive python shellCommand Prompt > manage.py shell
In[1]: from backendapp.models import menuIn[2]: print(menu.objects.all())<QuerySet[] >
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)>]>
In [6]: quit()
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 django.contrib import adminfrom backendapp.models import menu# Register your models here.admin.site.register(menu)
Command prompt> manage.py createsuperuser
Username(leave blank to use 'xxxxx'): xxxxxEmail address: xxxxx@xxxx.comPassword:Password(again):Bypass password validation and create user anyway? [y/N]: ySuperuser created successfully.
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.
In the next post, we will see how to query from the reactjs front end and present this data.



Comments
Post a Comment