Detailed explanation of django Model model layer
As the "brain center interface" of the Django framework, the Model layer is the bridge connecting business logic Python code and relational-database data. Today we will use a clear practical route to learn the core knowledge points of Django ORM and Model~
Course Objectives
- Understand the positioning and value of django ORM
- Master the basic definition syntax and field types of Model
- Proficient in database migration (from creating tables to maintaining table structures)
- Learn to use QuerySet to complete CRUD and common queries
Introduction to django ORM
ORM (Object-Relational Mapping) is not unique to Django, but it is one of the "most development efficient" modules in the Django ecosystem:
- It maps database tables to Python classes (Model we wrote)
- Map a record in the table to an instance of the class
- Encapsulate SQL's addition, deletion, modification, query, filtering, sorting, etc. into Python method/attribute calls
Why should we use it?
Definition of Model
Model class must be written in django applicationmodels.pyfile, and ** must inherit fromdjango.db.models.Model**。
The first complete Model
Let's first write an Article Management Model, covering basic fields, common field options,__str__method andMetakind:
High frequency common field types
Django has built-in dozens of field types, covering most development scenarios. Here are the most commonly used ones:
Database migration
The Model class is just a "data structure description" at the Python level. To actually turn it into a table in the database, a Migration operation must be performed.
Two-step core process of migration
1. Generate migration file (makemigrations)
This step will detectmodels.pychanges** and generate a Python script file (stored in the corresponding applicationmigrationsfolder), this script is "reversible", so you don't have to worry about changing the table structure.
2. Execute migration (migrate)
This step will read the migration file and translate it into SQL statements to actually create/modify/delete tables in the database.
Commonly used migration auxiliary commands
Check migration status
Rollback migration
Basic operations of QuerySet
Model classobjectsThe attribute is the Manager automatically generated by Django. All database operations must be called through it. The returned result is a QuerySet (which can be understood as a "delayed execution query set". The database will only be checked when the data is actually used, and the performance is very high).
Create record (Create)
Method 1:save()
Instantiate the Model class first and then call it manuallysave()This method is suitable for scenarios where instance attributes need to be modified and then saved.
Method 2:create()
directly through the managercreate()The method is created and saved, which is suitable for scenarios where no additional modification of attributes is required, and the code is more concise.
Query records (Retrieve)
Get all records
Get a single record
Notice:get()The method must return ** and can only return one record **. If there is none or multiple records, an exception will be thrown.
Get the first/last record
Filter query (filter())
filter()The method returns a QuerySet of multiple records that meet the conditions and supports chain calls.
Update records (Update)
Update a single record
andsave()The process of creating records is similar. First query the instance, modify the attributes, and thensave()。
Batch update
pass directlyfilter()+update()This method does not require querying the instance first, is more efficient, and is suitable for modifying a large number of records that meet the conditions.
Delete record (Delete)
Delete a single record
Query the instance first and then calldelete()method.
Batch delete
pass directlyfilter()+delete()Method, does not need to query the instance first, and is more efficient.
Course Summary
Today we started with the positioning of ORM and learned:
- How to define a complete django Model using Python classes
- Frequently used field types and common field options
- Two-step core process and auxiliary commands for database migration
- Basic CRUD operations of QuerySet (create, query, update, delete)
These are the core foundation of Django development. After mastering them, we can further learn about Model relationships, advanced queries, performance optimization, etc. ~

