How to Make Database Models in Django

Muskan Kalra
Towards Dev
Published in
5 min readMar 19, 2021

--

Photo by Emile Perron on Unsplash

In this blog, we will create database models and create a superuser to access them from the Django Administration Panel. Models is a class representing a table in our database. Django uses SQLite by default; other database types like MySQL, PostgreSQL, Oracle, etc., can also be used. SQLite is lightweight and doesn’t use a separate server; in this blog, we will be using sqlite3.

Prerequisites:

  1. Install Django, set up the virtual environment, and activate it.
  2. Start the project from the terminal(in the virtual environment):
django-admin startproject blogs

3. Start the django app from the terminal:

python manage.py startapp blog

We will now include this app in our project, in blogs/settings.py, under the installed apps, add the following statement:

INSTALLED_APPS = [
...
...
'blog.apps.BlogConfig',
]

Let’s Start

The django models store the data. The models are built-in feature provided by django for creating tables, fields, functions and various constraints. Django uses a library sqlparse for parsing the SQL statements.

Creating models in store/models.py:

In our blog app, we will create two models:

  1. Author- For storing the information of all the authors contributing for our blog. It has two fields: name(for author’s name) and category(for the category that the author is contributing, example- Web Development).
  2. Story- This model is for storing all the information about every story on the blog app, it contains: name(name of the story), published_date, autor(who wrote this medium story) and description(a brief description about what the story is about).

The code in blog/models.py file will look this:

from django.db import models


class Author(models.Model):
name = models.CharField(max_length=100, null=False)
# charField is for storing strings
category = models.CharField(max_length=200)

# the instances of the model
# will be renamed after author name
# in django admin panel
def __str__(self):
return str(self.name)


class Story(models.Model):
name = models.CharField(max_length=200, null=False)
published_date = models.DateTimeField(auto_now_add=True)
# auto_now_add automatically sets the time
# when the object is created

author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
# foreign key is used here for defining
# many-to-one relationships
description = models.TextField()
# textfield is used for a large description

def __str__(self):
return str(self.name)

Every model class is inheriting django.db.models.Model and the classes we made have some class variables, which are database fields. These fields are instance of Field class, example, CharField is used for storing strings, TextField is used for storing large text, DecimalField is used for decimal numbers, EmailField is used for email addresses and many more.

These field classes also have arguments that can be either optional or required, for example, Char_Field requires max_length, whereas null is an optional argument.

Activating Django Models

Everytime we have a change in our models, or like this time we created new models, we have to run the command of makemigrations as given below. Django stores the migrations, it is way to handles the details of our database schema on the disk.

We run migrate command to reflect these migrations in our database. Congratulations, your database is now created after this migrate command shown below.

Registering the models to the Django Admin

We have to tell the admin of the our blog app that we need an admin interface for our models, so we go to blog/admin.py and add register our models to the admin.

from django.contrib import admin
from . models import *
# import all the models from models.py file

# Register your models here.
admin.site.register(Author)
admin.site.register(Story)

Creating a superuser

We will create a user that has rights to log in to the database. To do this, run the python manage.py createsuperuser command and enter the username and a password to create a superuser.

(venv) C:\Users\Lucky\PycharmProjects\blogs>python manage.py createsuperuser
Username (leave blank to use 'lucky'): muskan
Email address: abc@xyz.com
Password:
Password (again):
Superuser created successfully.

Logging in the Django Admin

Let’s run the server and go to django admin panel. We can start the server by the following command from the terminal in the django project.

python manage.py runserver

Then we will go to the admin by opening , 127.0.0.1:8000/admin/ from the browser, it asks for the username and password of the superuser that we just created, we will enter the details and login.

After logging in, we see the two models that we created and two default models: Groups and Users that are provided by Django for authentication and authorization.

Creating an author and adding a story in the database:

Click on the authors model, there are no authors saved in the database yet. Let’s click on add author.

Add an instance of author and save it:

Similarly, you can create an instance for story and save it. Since author is a foreign key so we add the author that we just created above to this story.

Similarly, we can perform delete and update operations. We get couple of options like,

  1. Save and continue editing- Saves the object and stays on the same page.
  2. Save and add another- Saves the object and opens another blank form for a new object.
  3. Save- Saves the object and then it returns us one directory back, i.e., from where we can access all the objects of this type.
  4. Delete- Leads us to the page for confirmation of deleting the page and then after confirming, the object can be deleted.

References:

https://docs.djangoproject.com/en/3.1/intro/tutorial02/

https://docs.djangoproject.com/en/3.1/ref/models/fields/

--

--