A Django Blog In VS Code — Database Migrations & Queries
How To Create A Blog in VS Code — Part II— DjangoSeries Episode # 05
Hi, in this Python Django Tutorial we will deal with:
Theme: DATABASE - Migrations - ORM (Object Relational Mapper)Point 1: Database creations for our application using Django models;Point 2: Making queries - Use the Django ORM to query the database and filter through results.
Think ORM like this: it handles the small details so you can focus on the big picture of your project — the business logic that drives your site and is probably a lot more fun to deal with than the tiny particularities of forms.
Django ORM is an abstraction layer. It provides us with features like Querysets and migrations and these relations.
The ORM has many benefits engulfing those of migrations and Querysets.
We all use queries to retrieve data from the database. Querysets are Django’s way to retrieve data from the database. The Django ORM lets us use Querysets.
A Queryset is a list of objects of a model.
We use Querysets to filter and arrange our data. These make our work as a Python developer easier.
Querysets are generally associated with CRUD applications.
Let’s get started!
00#Step — This is a continuation of this post; get there and you are ready to fly on your own.
Django gives us an automatically-generated database-access API. Let’s create our model…
01#Step — Open blog/models.py
and type:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=64)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
02#Step —On Terminal, Ctrl+c (to kill the server), and Type:
python manage.py makemigrations
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Post
This will create an SQL Script for Post database on blog/migrations/
:
If we were building the database schema manually, we might write an SQL query or use a database management GUI to create the first table.
But in Django, you do things differently. First, you use a subcommand from the command-line utility that will generate instructions for building the table (makemigrations @ this step). And then, use another sub-command to execute those instructions (migrate @ step#4 below). These instructions are called a migration.
A migration is a set of instructions for moving your database schema from one state to another. Importantly, these instructions can be executed automatically as code.
03#Step — Now type:
python manage.py sqlmigrate blog 0001
BEGIN;
--
-- Create model Post
--
CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(64) NOT NULL, "content" text NOT NULL, "date_posted" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id");
COMMIT;
This command revels the Database SQL’s code that Django’s create for us :)
04#Step — Let’s migrate our database, on Terminal:
python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
05#Step — Let’s create a superuser for administrative managements:
python manage.py createsuperuser
Username (leave blank to use 'giljr'): j3
Email address: g***@gmail.com
Password:
Password (again):
Superuser created successfully.
06#Step — GoTo Terminals and type:
python manage.py shell
This opens up a terminal.
It allows you to work directly from the root folder of a Django project.
from blog.models import Post
from django.contrib.auth.models import User
User.objects.all()
User.objects.first()
User.objects.filter(username='j3')
user = User.objects.filter(username='j3').first()
user.id
user.pk
user = User.objects.get(id=1)
Post.objects.all()
post_1 = Post(title='Blog 1', content='First post content!', author=user)
post_1.save()
Post.objects.all()
post_2 = Post(title='Blog 2', content='Second post content!', author_id=user.id)
post_2.save()
Post.objects.all()
user.post_set.all()
user.post_set.create(title='Blog 3', content='Third post content!')
Post.objects.all()
exit()
Hint_0: You can copy and paste everything at once and hit enter on Terminal :)
These commands will create 3 posts in different ways. This is a way to manipulate your database via DB Django API.
Hint_1: to Clear python console on windows, type:
print(chr(27) + "[2J")
Hint_2: Clear screen in shell on ubuntu: Clear screen in shell type:
CTRL+L
# Here is my output in my terminal:
python manage.py shell
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Post
>>> from django.contrib.auth.models import User
>>> User.objects.all()
<QuerySet [<User: j3>]>
>>> User.objects.first()
<User: j3>
>>> User.objects.filter(username='j3')
<QuerySet [<User: j3>]>
>>> User.objects.filter(username='j3').first()
<User: j3>
>>> user = User.objects.filter(username='j3').first()
>>> user.id
1
>>> user.pk
1
>>> user = User.objects.get(id=1)
>>> Post.objects.all()
<QuerySet []>
>>> post_1 = Post(title='Blog 1', content='First post content!', author=user)
>>> post_1.save()
>>> Post.objects.all()
<QuerySet [<Post: Blog 1>]>
>>> post_2 = Post(title='Blog 2', content='Second post content!', author_id=user.id)
>>> post_2.save()
>>> Post.objects.all()
<QuerySet [<Post: Blog 1>, <Post: Blog 2>]>
>>> user.post_set.all()
<QuerySet [<Post: Blog 1>, <Post: Blog 2>]>
>>> user.post_set.create(title='Blog 3', content='Third post content!')
<Post: Blog 3>
>>> user.post_set.all()
<QuerySet [<Post: Blog 1>, <Post: Blog 2>, <Post: Blog 3>]>
>>>exit()
07#Step — Download DB Browser for SQL and points it to your db.sqlite3
file:
08#Step — GoTO blog/views.py ,
and import Post object and, change the code inside context (delete dummy code):
from django.shortcuts import render
from blog.models import Post
def home(request):
context = {
'posts': Post.objects.all()
}
...
This code uses DB Django API to request all registered posts and populate the context object direct from DB just created.
09#Step — Now in your Terminal, type:
python manage.py runserver
10#Step — Fixing Date Format;
Please, consult this table: date: Available format strings
One more modification. If you compare with the last view, you’ll see that it turns the date string into a long ugly string. Let’s fix it!
Modify on blog/templates/blog/
:
home.html
The modification boils down to where we show the date (post.date_posted)
11#Step — The last step: register the app in the admin site, so that the administrator will have access to the Post model;
Open django_projects/settings.py
and type:
from django.contrib import admin
from blog.models import Post
# Register your models here.
admin.site.register(Post)
Now you can actually update that blog post from within our admin page and we can also change the authors of these blogs and much services more…
That’s all Folks!
In the next #DjangoSeries Episode we can further improve our front-end, enhancing our Django framework with BOOTSTRAP & TAILWIND CSS.
See you around. Bye!
👉 git
Related Posts
00#Episode — DjangoSerie — Django Intro — How To Build your First App in Python Django Framework — DjangoSeries
01#Episode — DjangoSerie — Django MTV In VS Code — How To Install Django Inside Virtual VS Code
02#Episode — DjangoSerie — Can You Solve This in Python? — Here is A Basic Python Question!
03#Episode — DjangoSerie — JUNGLE-DJANGO Webpage! This Is My New Django Netflix Clone Page!
04#Episode — DjangoSerie — A Django Blog In VS Code — Quick Start! — Part_I
05#Episode — DjangoSerie — A Django Blog In VS Code — Database, Migrations & Queries — Part_II (this one :)
06#Episode — DjangoSerie — A Django Blog In VS Code — Bootstrap, Tailwind CSS — Part_III
07#Episode — DjangoSerie — A Django Blog In VS Code — Forms & Validations — Part_IV
08#Episode — DjangoSerie — A Django Blog In VS Code — Login & Logout — Part_V
09#Episode — DjangoSerie — A Django Blog In VS Code — Upload Profile Picture — Part_VI
10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII
11#Episode — DjangoSerie — A Django Blog In VS Code — Class-Based-View & CRUD — Part_VIII
12#Episode — DjangoSerie — A Django Blog In VS Code — Posts Pagination & Quick DB Population — Part_IX
13#Episode — DjangoSerie — A Django Blog In VS Code — Self-Service Django Password Reset — Part_X
14#Episode — DjangoSerie — A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Productio — Part_XI
Credits & References
Python Django Tutorial: Full-Featured Web App Part 5 — Database and Migrations by Corey Schafer
Making queries — by djangoproject.com
Awesome Django by William Vincent and Jeff Triplett.
Django ORM Tutorial — The concept to master Django framework
django-crispy-forms/django-crispy-forms Lead developer: Miguel Araujo
SQLite Database Browser by Mauricio Piacentini (@piacentini)
“We become what we think about” — Earl Nightingale
HowTo Run this Tutorial - From the Scratch - In your Machine:)Annotations: Quick Start - video #TakeTheFirstStepToLearnDjango0 - Download DJG_<previous>/Django_project from my git repo;
1 - On your desktop, create a dir and named it as Tutorial_#;
2 - Inside this paste the previous Django_project file;
3 - GoTo vscode Terminal (command prompt) and ...
4 - Run this quick_script
(copy/paste inside you terminal and hit enter and wait until
Pillow is up and running...):python -m venv djangoEnv
djangoEnv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install django
python -m django --version
pip install django-crispy-forms
pip install Pillow5- GoTo Step#01 of this tutorial.And you are good to go!
<edited: feb, 2023, add step 11>