Django at a glance (Part 2): Models Unchained

From (Part 1)

What is a model?

This represents the database layout. Usually a specific kind of object saved in the database and has columns (fields) and rows (data).

Database setup:

By default, the configuration uses SQLite, but can be changed to any db of choice, say postgresql. SQLite is included in Python, so you won’t need to install anything else.

Create post model:

Open the models.py file in the blog(app) folder.

from django.db import models

# Create your models here.

Then create a post model.

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
content = models.TextField()
date_created = models.DateTimeField(default=timezone.now)

Each model is a python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.

Migrate:

Migrations are how Django stores changes to your models.

The migrate command looks at the INSTALLED_APPS (in this case blog) setting and creates any necessary database tables.

By running makemigrations, you’re telling Django that you have made some changes to your models (in this case, created a new model) and you would like the changes to be stored as a migration.

python manage.py makemigrations
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Post

A file (0001_initial.py) is created in the migrations folder .

class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('content', models.TextField()),
('date_created', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

Each field is represented by an instance of a field class e.g.CharField for character fields and TextField for text. This tells Django what type of data each field holds.

The name of each Field instance becomes the column name in the db.

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations)

And runs them against your database, synchronizing the changes you made to your models with the schema in the database.

python manage.py migrate

Then

Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying blog.0001_initial... OK

Register models in admin.py:

from django.contrib import admin

# Register your models here.

Then

from django.contrib import admin
from blog.models import Post

# Register your models here.
admin.site.register(Post)

Now we can add a post from the admin dashboard with the specified fields

http://localhost:8000/admin/

Basic steps:

Create the post model (in models.py).
Run python manage.py makemigrations to create migrations for the model.
Run python manage.py migrate to apply changes to the database.

Happy coding, Waithira -:)