A Django model is a core component that Django employs to generate database tables, their fields, and diverse constraints. Put simply, Django Models serve as the SQL Database utilized within Django applications.
Django models represent database tables. They encapsulate the structure and behavior of the data you’re storing. Django's ORM (Object-Relational Mapping) system abstracts away much of the complexity of working directly with databases, allowing you to interact with your database using Python code.
1. Defining Models:
Models are typically defined in the models.py
file within each Django app. Each model class represents a database table, and each attribute of the class represents a database field.
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=100)
phone = models.IntegerField()
2. Fields:
Django provides various field types to represent different types of data such as text, numbers, dates, and relationships between models. Some commonly used field types include:
CharField
: For storing strings with a maximum length.IntegerField
,FloatField
,DecimalField
: For storing numeric data.DateField
,DateTimeField
: For storing dates and times.ForeignKey
,OneToOneField
,ManyToManyField
: For defining relationships between models.
3. Primary Keys:
By default, Django adds an id
field to each model as the primary key, which is an auto-incrementing integer. Each model in Django automatically gets an AutoField named id
if you don't explicitly define one. Therefore, there's no need to define another AutoField explicitly.
# id = models.AutoField()
4. Methods:
You can define methods within a model class to add behavior related to instances of the model. Common methods includes __str__
which returns a human-readable representation of the model instance.
5. Database Operations:
Once you've defined your models, you can use Django's migration system to create corresponding database tables and perform schema changes. You can interact with your database using Django's ORM, which allows you to create, read, update, and delete records.
Let's see makemigrations
and migrate
commands in Django using the example of the Employee
model we discussed earlier.
makemigrations: The
makemigrations
command is used to create migration files based on changes made to your models. When you modify your models (add, remove, or alter fields), Django doesn't immediately apply those changes to the database schema. Instead, it generates migration files that represent the changes you've made.suppose you add a new field
department
to yourEmployee
model:class Employee(models.Model): name = models.CharField(max_length=100) phone = models.IntegerField() email = models.EmailField() department = models.CharField(max_length=100) # New field
After making this change, you run the
makemigrations
command:python manage.py makemigrations
Django examines the current state of your models and compares it to the previous state stored in the migration files. It then generates a new migration file (e.g.,
0002_auto_20220320_1200.py
) that contains instructions for applying the changes.migrate: The
migrate
command is used to apply the migration files and synchronize the database schema with the current state of your models. When you runmigrate
, Django executes all unapplied migrations in the order they were created.After generating the migration file using
makemigrations
, you apply the changes to the database by running:python manage.py migrate
Django executes the migration file created earlier (
0002_auto_20220320_1200.py
in this case), which alters the database schema to include the newdepartment
field in theEmployee
table.
In short, makemigrations
is used to generate migration files based on changes to your models, while migrate
is used to apply those migration files and synchronize the database schema with your models. These commands are essential for managing database schema changes in Django projects.
Admin Interface: Django provides a built-in admin interface that allows you to manage your models via a web interface without writing any additional code. We will explore this topic in next blog