How To Create Django Models (Step by Step)

How To Create Django Models (Step by Step). Django models are pivotal to building robust and dynamic Django web apps. After all, these models help you define the structure and behaviour of your app. Not only do they shape the business logic, but they also streamline data management, facilitate querying, and improve code organization. By mastering Django models, you build highly adaptable and responsive web apps that meet your needs.

In this guide, we walk you through the process of creating Django models. You get clear explanations, examples, and code snippets. By the end, you are ready to start creating Data models for your Django apps. 

Shall we start with How To Create Django Models (Step by Step).

What are Django Models?

A Django model is a Python class that represents a database table. It defines the structure, behaviour, and relationships of tables in a database. To illustrate, let’s assume you own a shoe shop. Create a model that categorizes the shoes based on specific characteristics, such as brand name, size, material, and type. This model enables you to maintain a consistent and organized collection of shoes.

In the same way, Django models is a blueprints for storing and organizing information in a computer database. These models define how data should be structured and organized in the database. 

Advantages of Using Django Models

Here’s how using Django Models  helps to build web applications:

  • Simplifies development: It is easier to write Python but it also reduces errors and allows you to work more efficiently. You don’t have to keep on switching between languages. As a result, focus seamlessly on making the app work.
  • Consistency: SQL exhibits inconsistencies across various databases in syntax, supported features, and behaviour. Consequently, you have to create distinct sets of SQL statements for each database you deploy your app to. However, by using Django models, describe your data once and let Django handle the database-specific details.
  • Avoids Introspection: Every app has to dynamically query the database to obtain details about its structure, so it uses that information within the application code. This process often has a high overhead and potential issues. With Django models, data is explicitly described within the application making introspection unnecessary.
  • Version Control: By having the models defined in your code, it becomes easier to track and manage design changes. 
  • Advanced Metadata: Django models allow for the storage of extensive metadata beyond just the basic table and column definitions. Also, you have the flexibility to use custom data types, such as email addresses, that may not be readily available in traditional SQL databases.

We have arrived to the main part of article How To Create Django Models.

Creating a Django Model

To create your first model, you need to identify the key characteristics of the data you want to store in your database. For this tutorial, we use the shoe shop example in the previous section. We need the brand name, size, material, and type (sneakers, boots, sandals, and high heels). While it’s possible to have more properties, we stick to the essential ones.

Prerequisites

While you may have all the prerequisites in place, we go over all the basic steps involved in creating a Django model to make it easier to follow along. 

Set Up the Environment

Start off by creating a directory where we build the Django app. Open the terminal and choose a suitable location to create the directory using the following command:

				
					mkdir myShoeproject

				
			

Navigate to the directory you created above: 

				
					cd myShoeproject
				
			

Next, create a virtual environment called my_env. Use a name that’s more relevant to your project

				
					python3 -m venv my_env

				
			

Activate the virtual environment.  

				
					source my_env/bin/activate
				
			

After you’re done, the prompt should indicate that you’re in your virtual environment as shown in the image below.

Install Django in the virtual environment. 

				
					pip install Django
				
			

Create Django Project

It’s now time to create a new Django project. Run the following command: 

				
					django-admin startproject shoe_shop .
				
			

This command creates a shoe_shop directory within your current working directory as shown in the image below. We’ve included a dot at the end of the command to avoid having too many nested directories. Learn more about this process by checking out our in-depth guide on creating Django projects. 

Create a Django App

For this step, we create your Django app for managing the shoe catalogue. Inside your Django project, create a new app called “shoe_catalog” using the command:

				
					python manage.py startapp shoe_catalog
				
			

By executing this command, you create a default folder structure encompassing various Python files along with a management app that bears the same name as your project.

In the code block below, see the folder structure you’ll find in the project directory. Here’s a breakdown of the files: 

				
					shoe_shop/
│
├── shoe_catalog/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
│
└── manage.py
				
			
  • shoe_shop : is the root directory of your Django app. It contains all your project files. 
  • shoe_catalog: is the Python package for your project. 
  • __init__.py: is a Python initialization file that marks the directory as a Python package.
  • asgi.py: used for running a Django project with ASGI (Asynchronous Server Gateway Interface) servers.
  • settings.py: contains the configuration settings for your project as a whole.
  • urls.py: responsible for defining the URL patterns and routing in your Django project, ensuring that incoming URLs are correctly mapped to the appropriate views for processing.
  • wsgi.py: used for running the project on WSGI (Web Server Gateway Interface) servers.
  • manage.py: serves as the command center of your Django project.

Update Settings

Adding your app to the settings.py file allows Django to include your app’s functionality and make it available within the project.

Open the settings.py file. Under INSTALLLED_APPS add the name of the app to the list as a string.  Here’s an example of how the INSTALLED_APPS list may look after adding the “shoe_catalog” app:

				
					# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'shoe_catalog',
]
				
			

Define the Model Class

Now to the meat and bones of the tutorial – defining the Django model fields.  Open the models.py file and define the fields that represent the attributes of the shoes, including “brand”, “size”, “shoe type”, and “material”. Copy and paste the code below the “Create your models here” comment.

				
					from django.db import models
# Create your models here.
class Shoes(models.Model):
    brand = models.CharField(max_length=100)
    size = models.IntegerField()
    shoe_type = models.CharField(max_length=100)
    material = models.CharField(max_length=100)

				
			

In this example, we have defined a Shoes model. The brand, size, and material fields are all CharField, which is a field that stores character data, and the size field is an IntegerField, which is a field that stores integer data.

Make and Apply Migrations

We’ve just made changes to models.py, but the database isn’t aware of the changes. We, therefore, need to perform migrations. We need to run the migrate command to create a table in the database for the shoes model with columns for brand, size, shoe type, and material. 

Generate the initial database migration for the Shoes model by running the command:

				
					python manage.py makemigrations shoe_catalog
				
			

Here’s the output you should expect on the terminal window: 

				
					Migrations for 'shoe_catalog':
  shoe_catalg/migrations/0001_initial.py
    - Create model brand
    - Create model size
    - Create model shoe_type
    - Create model material
				
			

Apply the generated migration to create the corresponding database table by running:

				
					python manage.py migrate
				
			

Use the Model

To retrieve, update, or delete the records you created above, we need to register the Shoes model in admin.py. Add the code appearing under the “Register your models here” comment. 

				
					from django.contrib import admin
# Register your models here.
from .models import Shoes
admin.site.register(Shoes)
				
			

Next, create a superuser by running the following command in the terminal:

				
					python manage.py createsuperuser
				
			

Enter your desired username, email address, and password when prompted. 

Run the server with the command shown below:

				
					python manage.py runserver localhost:8000
				
			

Now open your browser and navigate to localhost:8000. Remember, use any other host in place of localhost. You should see the following page:

Open your browser and navigate to the Django admin page (localhost:8000/admin/). Use the credentials you created above. You see the Shoes model. 

Thank you for reading How To Create Django Models (Step by Step). We shall conclude. 

How To Create Django Models (Step by Step) Conclusion

Creating Django models is a crucial aspect of building web applications with Django. With this guide, structure your data, define its attributes and relationships, and leverage Django’s powerful database capabilities. Get the skills to build custom web applications by setting up, migrating, and utilizing Django models effectively.

Avatar for Richard Kanyoro
Richard Kanyoro

The world’s biggest problems can be solved by progressively solving the little ones. I write to help people solve the “little” tech problems they face.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x