model
ORM understanding
- ORM concept
Object Relational Mapping (ORM) mode is a technology to solve the mismatch between object-oriented and relational databases.
Simply put, ORM automatically persists the objects in the program to the relational database by using metadata describing the mapping between the object and the database.
ORM acts as a bridge between the business logic layer and the database layer.
- Origin of ORM
Let us start with O/R. The letter O originates from "Object", and R comes from "Relational".
Object and relational databases are involved in almost all software development processes. At the user level and business logic level, we are object-oriented. When the object's information changes, we need to store the object's information in a relational database.
According to the previous method of development, programmers will mix many SQL statements in their business logic codes to add, read, modify, and delete related data, and these codes are usually repeated.
- Advantages of
ORM The main problem that ORM solves is the mapping of objects and relationships. It usually maps a class to a table one-to-one. Each instance of the class corresponds to a record in the table, and each attribute of the class corresponds to each field in the table.
ORM provides a mapping to the database, instead of writing SQL code directly, you only need to manipulate the data from the database like an operating object. Let software developers focus on the processing of business logic and improve development efficiency.
Define the model
The relationship between models, attributes, tables, and fields:
a model class corresponds to a table in the database, and the attributes defined in the model class correspond to a field in the model comparison table
Define attributes
创建模型类
元选项
在模型类中定义Meta类,用于设置元信息
示例:
class Meta:
db_table = "students"
ordering = ['id']
db_table
定义数据表名,推荐用小写字母,数据表名默认为项目名小写_类名小写
ordering
对象的默认排序字段,获取对象的列表时使用
示例:
ordering['id'] id按升序排列
ordering['-id'] id按降序排列
注意:排序会增加数据库开销
Model member
- Class attribute
- Object is an object of the Manager type, which is used to interact with the database. When the model class is defined without specifying a manager, Django will create a manager named objects for the model.
- If the user wants to customize the manager:
# 自定义模型管理器后,object就不存在了
stuObj = models.Manager()
- Custom Manager Manager class
class StudentsManager(models.Manager):
def get_queryset(self):
return super(StudentsManager, self).get_queryset().filter(isDelete=False)
- The model manager is the django model that interacts with the database. A model can have multiple managers
- effect:
- Add additional methods to the manager
- Modify the original query set returned in the manager and rewrite the get_queryset() method
- Create an object
- The purpose of creating objects is to add data to the database
- When creating an object, Django will not operate on the database. It will interact with the database after calling the save() method and save the object to the database.
- Add a class method to the model
# 定义一个类方法创建对象
@classmethod
def createStudent(cls,name,age,gender,contend,grade,isD=False):
stu = cls(sname=name,sage=age,sgender=gender,scontend=contend,sgrade=grade,isDelete=isD)
return stu
- Add a method to the manager
def createStudent(self,name,age,gender,contend,grade,isD=False):
stu = self.model()
stu.sname = name
stu.sage = age
stu.sgender = gender
stu.sgrade = grade
stu.isDelete = isD
return stu
3.4 Both methods can be called to create objects
- Query object
- Call the filter method on the manager to return the query set
- After the query set is filtered by the filter, a new query set is returned, so it can be written as a chain call
- Lazy execution (creating a query set will not bring any data access, until the data is called)
- The case of direct access to the data:
1. Iteration
2. Serialization
3. Combined with if - The method of returning the query set is called filter
1. all(): returns all data in the query set
2. filter(): keeps the data that meets the conditions
3. filter(key=value)
4. filter(key=value, key= Value)
5. filter(key=value).filter(key=value) and the relationship
6. exclude(): filter out those that meet the conditions
7. order_by(): sort
8. values(): a piece of data is a dictionary, returns a list
9. get () returns an object that satisfies the conditions Note: If the object is not found eligible, will lead to a model class .DoesNotExist abnormal; if it finds more than one object, can cause abnormal model class MultipleObjectsReturned
10. count (): Returns the number of objects in the query set
11. first(): returns the first object in the query set
12. last(): returns the last object in the query set
13. exits(): judges whether there is data in the query set, and returns True if there is data , Otherwise it returns False. - Limit query set The
query set returns a list, you can use the subscript method to limit, which is equivalent to the limit statement in sql.
Note: the subscript cannot be a negative number.
Example: studentsList = Students.stuObj2.all()[0:5] - Query set cache
overview: Each query set contains a cache to minimize access to the database. In the newly created query set, the cache is empty for the first time, and the first time the query set is evaluated, data caching will occur, and Django will The queried data is cached and the query result is returned. Future queries directly use the cache of the query set
Field query
- Overview
- The where statement in sql is implemented as a parameter of the methods filter(), exclude(), get()
- Syntax: attribute name __ comparison operator = value
- Foreign key: attribute name_id
- Escaping: similar to the like statement in sql, like the relevant situation depends on my brother,% is for matching points, the% in the matching data is used (where like “%”), filter(sname__contains="%")
- Comparison operator
- exact: judgment: case sensitive-
filter(isDelete=False) - contains: whether to include, case sensitive-
studentsList = Students.stuObj2.filter(sname__contains="sun") - startswith, endswith: start or end with value, case sensitive
(the above four with i in front of it means case insensitive iexact,icontains,istartswith,iendswith) - isnull,isnotnull: Is it empty-
filter(sname__isnull=False) - in: Whether to be included in the range
- gt is greater than, gte is greater than or equal to, lt is less than, lte is less than or equal to
- year,month,day,week_day,hour,minute,second
-studentsList = Students.stuObj2.filter(lastTime__year=2017)
- exact: judgment: case sensitive-
- Cross-relational query
- Aggregate function
- Use the aggregate function to return the value of the aggregate function
Avg
Count
Max
1. maxAge = Student.stuObj2.aggregate(Max('sage'))
2. maxAge is the maximum sage.
Min
Sum - The F object
can be compared with the model's A attribute and B attribute:
from django.db.models import F,Q
def grades1(request):
g = Grades.objects.filter(ggirlnum__gt=F('gboynum'))
print(g)
# [<Grades: python02>,<Grades: python03>]
return HttpResponse("OOOOOOOo")
支持F对象的算术运算
g = Grades.objects.filter(ggirlnum__gt=F('gboynum')+20)
- Q object
Overview: the keyword parameter of the filter method, and the condition is the And mode.
Requirement: perform or query
Solution: use Q object
studentsList = Students.stuObj2.filter(Q(pk__lte=3) | Q(sage__gt=50))
return render(request, 'myApp/students.html', {
"students": studentsList})
When there is only one Q object, it is used for normal matching conditions studentsList = Students.stuObj2.filter(~Q(pk__lte=3))
~Q is the inverse