A Django model is a single source that defines the information about your data. Each model in Django is a Python class that subclasses django.db.models.Model
.
A model in Django is used to create a table in the database. This means that each model maps to a single table in the database. The fields and behaviors defined in each model determine the type of data that can be stored in these tables in the database.
Consider a model for students and teachers in a particular school. There is a relationship between these two models, which is a one-to-many relationship, where one teacher caters to many students.
from django.db import modelsclass Teacher(models.Model):first_name = models.CharField(max_length = 10)last_name = models.CharField(max_length = 10)email = models.EmailField(max_length = 20, unique = True)d_o_b = models.DateTimeField()address = models.CharField(max_length = 200)def __str__(self):return f'{self.first_name} {self.last_name}'class Student(models.Model):first_name = models.CharField(max_length = 10)last_name = models.CharField(max_length = 10)email = models.EmailField(max_length = 20, unique=True)teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True)is_foreign_student = models.BooleanField(default = False)d_o_b = models.DateTimeField()address = models.CharField(max_length = 200)class_grade = models.IntegerField()CGPA = models.DecimalField(max_digits = 3, decimal_places=2)def __str__(self):return f'{self.first_name} {self.last_name}'
Notice that these models are Python classes, and the attributes of the classes are the fields on the database table.
The field types below determine the type of data that can be stored in these fields:
CharField
: This field only takes the equivalent of Python string type values.
IntegerField
: This field only takes integer type values.
DateTimeField
: This field only takes date/time type values.
EmailField
: This is a CharField
that is modified with a validator to only take email addresses.
BooleanField
: This field only takes boolean type values, which can be true
or false
.
DecimalField
: This field only takes decimal type values.
The relationship between the student
and teacher
tables is created with models.ForeignKey
, which points the student
table to the teacher
table.
The teacher
field in the student
table is the foreign key for the student
table. Since we do not indicate any primary keys for these models, Django
will automatically create unique primary key ID fields for these models.
Makemigrations
and migrations
Makemigrations
and migrate
are commands that are used to interact with Django models.
Makemigrations
: This command prepares a makemigrations
file for our new model, or creates a new migrations file for any changes if the models have been modified. This command does not create or affect these changes to the database.
Migrate
: The migrate
command runs the instructions defined in the recent migrations file on the database.
Let’s create a database for the myapp
app. We will be using the Python built-in SQLite3
for our database.
Run the migrate
command on your terminal to create your database.
Make sure to cd
(change directory) into the file level where your manage.py
file is before running any commands involving manage.py
.
python3 manage.py migrate
You should get a response similar to the one below:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Observe that your file structure has been modified, and a new db.sqlite3
file has been added to your file structure. This db.sqlite3
file is your local database on your computer, and the file is encrypted so we can’t read its contents. This command makes the initial connection with the database.
You have to register your myapp
app in the INSTALLED_APP
section in myproject/settings.py
to write these models into your database file, as shown below:
INSTALLED_APPS = [
'myapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Notice that the
admin
,auth
, andcontenttype
apps have been pre-installed in this section.
makemigrations
command in the terminal:python manage.py makemigrations
Migrations for 'myapp':
myapp/migrations/0001_initial.py
- Create model Teacher
- Create model Student
In your myapp/migrations
folder, a new migrations file 0001_initial.py
will be created. You can view this file, but do not edit it.
The file contains the equivalent SQL
command for creating these tables in the database.
Now, run the migrate
command to create these tables in the database.
This response is displayed in the terminal:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, myapp, sessions
Running migrations:
Applying myapp.0001_initial... OK
myapp.admin.py
, as shown below:from django.contrib import admin
from.models import Teacher, Student
admin.site.register(Student)
admin.site.register(Teacher)
Create a superuser by running the following command on your terminal, and follow the prompt on the terminal:
python3 manage.py createsuperuser
Follow the prompt correctly to create the superuser account.
Finally, start up your server with this command:
python3 manage.py runserver
Enter this URL in your web browser to go to the admin page: http://127.0.0.1:8000/admin
.
Login with your superuser details to view your tables in the admin dashboard.
Your admin dashboard should look like the images below.
I hope you now understand what a basic Django app model is, the difference between the makemigrations
and migrate
commands, and what these commands are used for.