Django Model :-
In Django, a model is a class which is used to contain essential
fields and methods.Each model class maps to a single table in the
database.
Django Model is a subclass of django.db.models.Model and each field
of the model class represents a database field (column).
Django provides us a database-abstraction API which allows us to
create, retrieve, update and delete a record from the mapped table.
Model is defined in Models.py file. This file can contain multiple
models.
Django Model Example:-
Suppose We created a model Student that contains the following code
in models.py file.
//models.py
from django.db import models
class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
contact = models.IntegerField()
email = models.EmailField(max_length=50)
age = models.IntegerField()
After that apply migration by using the following command.
>>>python manage.py makemigrations mysite(app_name)
It will create a table mysite_student.
This model will create a table into the database that looks
like below.
CREATE TABLE mysite_student (
"id" INT NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL,
"contact" INT NOT NULL,
"email" varchar(50) NOT NULL,
"age" INT NOT NULL
);
The created table contains an auto-created id field. The name
of the table is a combination of app name and model name.