ORM add, delete, modify and check
Two ways to add
- save()
- Save by model class
Note: The operation of adding foreign key information is as follows:
herozhu = HeroInfo.objects.create(
hname = "猪八戒",
hgender = 0,
hdesc = 'houhouhou',
hbook = book
)
herosha = HeroInfo.objects.create(
hname = "沙悟净",
hgender = 1,
hdesc = '呵呵',
hbook = book
)
Modifying data
There are two ways to modify and update:
1) Modify the attributes of the model class object, and then execute the save() method.
2) Use the model class.objects.filter().update(), which will return the number of rows affected.
At this time the database content Both are modified successfully to
delete the data.
There are two ways to
delete
: 1) Model class object delete the database content at this time:
2) Model class.objects.filter().delete()
at this time database content:
basic query
Usage:
get:查询单一结果,如果不存在会抛出DoesNotExist异常,如果存在多个结果会报MultipleObjectsReturned异常
all:查询多个结果
count:查询结果数量
Filter query When
querying, __ (double underscore) means judgment
- filter: filter out multiple results
- Exclude: Exclude the remaining results that meet the conditions
- get: Filter a single result
- exact: indicates that the judgment is equal
- contains: indicates whether it contains
- startswith and endswith: start or end with the specified
- isnull: is it null
- exclude: filter
- in: Whether to be included in the range
- gt: greater than
- gte: greater than or equal to
- lt: less than
- lte: Less than or equal to
F and Q objects
1) F: The
previous query is to compare the properties of the object with the constant value. How do the two properties compare? Answer: Use F objects, which are defined in django.db.models.
Syntax: F (attribute name)
导包:from django.db.models import F,Q
2)Q:
Multiple filters are called one by one to indicate the logical and relationship, which is the same as the and keyword in the where part of the SQL statement.
Implement the not and or
aggregate function and sort function in mysql
1) Aggregate function:
use aggregate() filter to call aggregate function. Aggregate functions include: Avg average, Count number, Max maximum, Min minimum, Sum summation, which are defined in django.db.models.
Sort:
use order_by to sort the results