Django Models


In this chapter, you will learn about what all ORMs are supported by Django.

Django Models 

Django proposes database access with an abstraction layer called Object-Relational Model (ORM). This allows you to use the Python implementation object in order to access the data so you don’t have to worry about How to use a database. With ORM, we don’t need to use the SQL query for simple and slightly complex actions. But how to work with ORM? That’s where models come in handy. You can say they simply create a link between our views and database.


A model is pretty much just an object that inherits from Model class. This Model class is specifically designed and provided by Django for the sake of data persistence. Think of the model as a table in the database and the properties we define for our model will map the fields in the table.
In this chapter, our main focus will be,
  • set up and access database
  • database migrations
  • creating simple models
  • using administration module

Database setup

Open and scroll all the way down to the DATABASES. You should see this,
  1. DATABASES = {  
  2. 'default': {  
  3.    'ENGINE''django.db.backends.sqlite3',  
  4.    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),  
  5. }  
  6. }  
Let’s see what it says,
  • The ENGINE property specifies the type of database to be used.
  • The NAME property defines the path and final name of the SQLite database.
These are the default settings for our project. You are more than welcome to get your hands dirty and configure any other database (Django does support them all) but for the sake of simplicity, I’m going to stick with the default settings.


Migrations are Django’s way of transmitting changes (like creating a field, deleting a model, etc.) that you make to your models. Whenever you create a model or do some changes to it, you need to tell Django to make the changes in your database by applying migrations. But what if we don’t apply them?
While running your app, you would have noticed somewhat like this.
You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Let’s try something, run your application, and navigate to Oops! You’re going to run into an error.
What just happened?
Remember I talked to you about building in the admin panel? We just tried to access that but here’s a catch. Django does not know that we want that functionality in our app. Why? Because we haven’t applied any migrations and so that table is not being created in our project. Let’s apply migrations and see what happens.
Enter the following command (you should be in your project directory.)
  1. python migrate  
and you’ll see a screen saying that all those migrations are being applied.
Run your app again and try to access the admin panel. This time, you’ll see a login page instead of an error. But we can’t log in because we haven’t set any admin user. We’ll get back to the admin user part but let us first create a few more models.

Creating simple models

Let’s just say we want to make our site a platform where users can add their favorite movies. For this purpose, we need a user who could mark the movie as a favorite and the movie that is being marked. We need to create two models: User and Movies. Open webapp/ file. It looks like this.
  1. from django.db import models  
  3.  # Create your models here.  
The above line of code allows us to import the base model of Django. Now, all we need to do is to define our very own models.

User model

To create the User model, what data do you think we would need to keep? It could be the user’s real name, username, password, etc. Let’s create the model and see the rest.
Enter the following in your file.
  1. class User(models.Model):      
  2.      name = models.CharField(max_length=50)      
  3.      username = models.CharField(max_length=25)      
  4.      password = models.CharField(max_length=25)        
  5.      email = models.EmailField    
In the preceding code, our User is inheriting from Model class. We also added a few attributes to the class and specified the values. As for our first field, the name is a character string type with a maximum length of 50 characters. Django offers different field types as you might have noticed in the above code. These fields most commonly include Char, Email, Integer, etc.


For our movie model, we will require the title, description and genre, and actors.
Use the following code to define the project model.
  1. class Movies(models.Model):    
  2.      title = models.CharField(max_length=50)    
  3.      description = models.CharField(max_length=1000)    
  4.      genre = models.CharField(max_length=250)  
  5.      lead_actor = models.CharField(max_length=250)   
For now, we have our models created as User and Movies.
Before seeing this all in action, we need to first add our app to installed apps. Open and add the name of your app (webapp in this case) in INSTALLED_APPS.
  1. INSTALLED_APPS = [    
  2.      'django.contrib.admin',    
  3.      'django.contrib.auth',    
  4.      'django.contrib.contenttypes',    
  5.      'django.contrib.sessions',    
  6.      'django.contrib.messages',    
  7.      'django.contrib.staticfiles',    
  8.      'webapp.apps.WebappConfig'    
  9.  ]   
Next, apply migrations by entering the following commands.
  1. python makemigrations  
This command is responsible for creating new migrations based on the changes we have made to our models. After executing the above command you’ll see the following message appearing on your screen.
  • Create model Movies
  • Create model User
Now enter the following command.
  1. python migrate  
You should see this message after the command is executed.
Applying webapp.0001_initial... OK
All done!!!!
But wait for a second; what is it webapp.0001_initial? If you see your project directory once again, a file naming is created under webapp/migrations which is nothing but pretty much a projection of your created model but with migrations being applied. This is one of the coolest features that Django offers that it keeps the history of your migrations. Now, if you create some other models or make some changes, the second file would be created under the same tab. If anything goes wrong at any point, you can simply look it up and you don’t have to do anything extra. Sweetness overloaded.
Also, notice that you didn’t have to execute even a single query of SQL. Django did that for you. If you want to check that just execute the following command.
  1. python sqlmigrate webapp 0001  
and you’ll see all the SQL queries that are executed behind the back.

Admin Module

So far so good but how to see these models in the database? Seems like it’s time to continue with our admin user. Run the following command to set up the admin.
  1. python createsuperuser  
It will ask you for your username, email, and password. Enter your desired credentials and you’re good to go.
One last thing before you see things in action. You need to register your models with the admin. Open webapp/ file and enter the following snippet. 
  1. from django.contrib import admin  
  2. from .models import *  
Now try accessing the admin panel again at and log in using the credentials you set. You should see your models (User, Movies) under webapp.
You’re free to populate it with some random data for testing and playing around. 


In the next article, we will start working with the Database in Django.
Mehreen Tahir
389 6.3k 422.3k
Next » Migration Of Database Models