Django Models

Hey there!

Well, if you think this is another article by a Django obsessed person, let me say that was an intelligent guess. I’m continuing my Django article series with this fifth one.

Last time, we worked with the templates but our website only contains static data. I was just scrolling down my feed when I came across this.

 

Just ignore his face. But this meme hit me hard and I thought to take our website a step ahead; let’s store data so as to automate all the tasks; so we’ll be looking into the database schema.

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.

Models

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 article, our main focus will be,

  • set up and access database
  • database migrations
  • creating simple models
  • using administration module

Database setup

Open settings.py 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

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 http://127.0.0.1:8000/admin/. 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 manage.py 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 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 there favorite movies. For this purpose, we need a user who could mark the movie as favorite and the movie that is being marked. We need to create two models: User and Movies. Open webapp/models.py file. It looks like this.

  1. from django.db import models  
  2.    
  3.  # Create your models here.  

The above line of code allows us to import 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 user’s real name, username, password etc. Let’s create the model and see the rest.

Enter the following in your models.py 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
  6.   

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, 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.

 model

For our movie model, we will require the title, description and genre and actors.

Use the following code to define 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 settings.py 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 manage.py makemigrations  

This command is responsible for creating new migrations based on the changes we have made to our models. After exeuting the above command you’ll see following message appearing on your screen.

webapp\migrations\0001_initial.py

  • Create model Movies
  • Create model User

Now enter the following command.

  1. python manage.py 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 0001_initial.py 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 manage.py 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 manage.py createsuperuser  

It will ask you for 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 admin. Open webapp/admin.py file and enter the following snippet. 

  1. from django.contrib import admin  
  2. from .models import *  
  3.    
  4.  admin.site.register(User),  
  5.  admin.site.register(Movies),    

Now try accessing the admin panel again at 127.0.0.1:8000/admin/ and login 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. But the fun’s not over yet. It's all good for the admin but how will users enter the data or retrieve it back from the database? We’ll see that in next article. Until then, happy coding to you all. :)


Similar Articles