Chapter-22

Models

22.1. Model :-

A model is the single, definitive source of information about your data.
It contains the essential fields and behaviors of the data you’re storing.
Generally, each model maps to a single database table.

22.2. Model Class:-

Model class is a class which will represent a table in database.

Each model is a Python class that subclasses django.db.models.Model

Each attribute of the model represents a database field.

With all of this, Django gives you an automatically-generated database - access API Django provides built-in database by default that is sqlite
database.

We can use other database like MySQL, Oracle SQL etc.

22.3. Create Our Own Module Class :-

22.4. Rule :-

Field Name instantiated as a class attribute and represents a particular table’s Column name.

Field Type is also known as Data Type.

A field name cannot be a Python reserved word, because that would result in a Python syntax error.

A field name cannot contain more than one underscore in a row, due to the way Django’s query lookup syntax works.

A field name cannot end with an underscore.

22.5. How to Use Modules :-

Once you have defined your models, you need to tell Django you’re going to use those models.

Open settings.py file

Write app name which contains models.py file in INSTALLED_APPS = [ ]

Open Terminal

Run python manage.py makemigrations

Run python manage.py migrate

22.6. Migrations :-

Migrations are Django’s way of propagating changes you make to your models (adding afield, deleting a model, etc.) into your database schema.

makemigrations – This is responsible for creating new migrations based on the changes you have made to your models.

migrate – This is responsible for applying and unapplying migrations.

sqlmigrate – This displays the SQL statements for a migration.

showmigrations – This lists a project’s migrations and their status.

22.7. makemigrations and migrate :-

22.8. display SQL statement :-

22.9. Built-in Field Options :-

22.10. Model Operation :-

PreviousNext