database
1. Define the model class
Define the model class in models.py, inherited from models.Model
from django.db import models
# Create your models here.
class 模型类A(models.Model):
# 创建字段,字段类型...
name = models.CharField(max_length=10)
class 模型类B(models.Model):
gender = models.BooleanField()
# 外键约束(B中某物属于A中某类)
book = models.ForeignKey(模型类A,on_delete=models.CASCADE)
Model class optimization
class 模型类A(models.Model):
name = models.CharField(max_length=10)
# ------------------------------------------
def __str__(self):
"""将模型类以字符串的方式输出"""
return self.name
1) Primary key
Django will create an auto-growing primary key column for the table. Each model can only have one primary key column. If the option sets a certain attribute as the primary key column, Django will no longer create an auto-growing primary key column.
The attribute of the primary key column created by default is id, which can be replaced by pk (primary key for full screen)
2) Property naming restrictions
Cannot be a reserved keyword of python
Continuous underscores are not allowed (decided by django query method)
When defining attributes, you need to specify the field type, syntax: attribute=models. Field type (option)
Field Type
Type Description
AutoField Auto-growing IntegerField, usually you don’t need to specify it. If you don’t specify it, Django will automatically create an auto-growing attribute named id.
BooleanField. The value is True or False.
NullBooleanField supports Null, True, and False
CharField strings. max_length parameter indicates the maximum number of characters
TextField large text fields, used typically in excess of 4000 characters
IntegerField integer
DecimalField decimal floating point, represents the total number of bits max_digits parameter, the parameter bits represent the fractional decimal_places
FloatField float
DateField date, each represents a parameter auto_now When saving the object, this field is automatically set to the current time, which is used for the timestamp of the "last modified". It always uses the current date and the default is False; the parameter auto_now_add means that the current time is automatically set when the object is created for the first time. The timestamp used to create, it always uses the current date, the default is False; the parameters auto_now_add and auto_now are mutually exclusive, the combination will cause an error.
TimeField time, the parameter is the same as DateField
DateTimeField date and time, the parameter is the same as DateField
FileField upload file field
ImageField Inherited from FileField, verify the uploaded content to ensure that it is a valid image
Options
Option description
null If True, it is allowed to be blank, the default value is False
blank If True, the field is allowed to be blank, the default value is False
db_column field name, if not specified, the name of the attribute
db_index If the value is True, then an index will be created for this field in the table, the default value is False
default default
primary_key If True, the field will become the primary key field of the model, the default value is False, generally used as an option of AutoField
unique If it is True, This field must have a unique value in the table, the default value is False
Foreign key
When setting the foreign key, you need to specify the on_delete option to specify how to deal with the data in the foreign key reference table when the main table deletes data. django.db.models contains optional constants:
- CASCADE cascade, delete the data in the foreign key table together when deleting the main table data
- PROTECT protection, by throwing a ProtectedError exception, to prevent the deletion of the data in the main table that is applied by the foreign key
- SET_NULL is set to NULL, only available when the field null=True allows null
- SET_DEFAULT is set to the default value, only available when the field is set to the default value
- SET() is set to a specific value or calls a specific method
- DO_NOTHING does nothing. If the database indicates cascading beforehand, this option will throw an IntegrityError exception
2. Configure the database
The sqlite database is used by default in setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Use mysql database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'mysql', # 数据库用户密码
'NAME': 'book' # 数据库名字
}
}
3. Model migration
Generate migration file: Generate table creation statement based on model class
python manage.py makemigrations
Perform migration: create a table in the database according to the statement generated in the first step
python manage.py migrate
4. Run the test
Need to install the client driver of the MySQL database
pip install mysqlclient==1.4.6 -i https://pypi.tuna.tsinghua.edu.cn/simple/
If you still report an error, you need to install libmysqlclient-dev (in the virtual machine)
sudo apt-get install libmysqlclient-dev
5. Database operations
increase
1)save
>>> from 子应用名.models import 类名
>>> 对象a = 模型类A(
... name='python入门',
... pub_date='2010-1-1'
... )
>>> 对象a.属性1 = 属性值
>>> 对象a.属性2 = 属性值
>>> 对象a.save()
2)create
>>> 模型类A.objects.create(
... name='itheima',
... book=book
... )
change
1)save
Modify the attributes of the model class object, and then execute save()
>>> 对象a = 模型类A.objects.get(属性='原信息')
>>> 对象a.属性 = '新信息'
>>> 对象a.save()
2)update
>>> 模型类A.objects.filter(属性='原信息').update(属性='新信息')
delete
1) Model class object delete
>>> 对象a = 模型类A.objects.get(属性='信息')
>>> 对象a.delete()
2) Model class.objects.filter().delete()
>>> 模型类A.objects.filter(属性='信息').delete()
check
Basic query
1) Get query a single result, if it does not exist, it will throw a model class. DoesNotExist exception
>>> 模型类A.objects.get(属性=信息)
2) all query multiple results
>>> 模型类A.objects.all()
3) count query quantity
>>> 模型类A.objects.count()
4) filter query all
>>> 模型类A.objects.filter()
5) exclude() is not equal to negation
>>> 模型类A.objects.exclude()
Filter query
属性名称__比较运算符=值
# 属性名称和比较运算符间使用两个下划线,所以属性名不能包括多个下划线
BookInfo.objects.filter(id__exact=1)
可简写为:
BookInfo.objects.filter(id=1)
比较运算符 功能 举例
exact 相等 可简写为:id=1
contains 是否包含 __contains='传'
startswith、endswith 指定开头或结尾 __endswith='部'
isnull 是否为空 __isnull=True
in 是否在范围内 __in=[1,3,5]
gt,gte,lt,lte 大于,大于等于,小于,小于等于 __gt=3
year,month,day,week_day,hour,minute,second date and time type __year=1980
Example: Query books published after January 1, 1990.
>>> BookInfo.objects.filter(pub_date__gt='1990-1-1')
F Realize the comparison between attributes
from django.db.models import F,Q
# 阅读量大于等于2倍评论量
BookInfo.objects.filter(breade__gte = F('bcomment'))
Q implements not and or in mysql
Symbol function
& and
| or
~ not
Aggregate function.aggregate()
Return a dictionary
Avg The average
Count quantity is generally not used, directly use count()
Max Max aggregate(Max('attribute'))
Min Min
Sum sum
Sort.order_by()
Ascending order: .order_by('attribute')
Descending order: .order_by('-attribute rd')
Associated query
Get the data corresponding to 1
# 1的对象.多的模型类小写_set.all()
bookinfo.heroinfo_set.all()
Get the data of the side with more corresponding 1
# 直接使用外键
heroinfo.bookinfo
heroinfo.bookinfo_id
Related filter query
The inquiry hero is Guo Jing's books
bookinfo.object.filter(heroinfo__name='郭靖')
The description of the query book contains'palm'
bookinfo.objects.filter(heroinfo__desc__contains='掌')
The model condition with more queries is to judge the attributes of one side
The condition uses the dictionary of the associated model class 1 the foreign key name of the model class __1 the attribute name of the model class __ conditional operator = value
Query all the heroes of the eight dragons
heroinfo.objects.filter(book_title='天龙八部')
View the location of the MySQL log
cat mysql.log
QuerySet
1. Lazy execution
The creation of a query set will not access the database, and will not access the database until it is called. The calling conditions include iteration, serialization, and combined use with if.
books = bookinfo.objects.all() # 这时查看MySQL日志发现没有执行
for b in books:
print(b.title) # 执行了语句
2. Cache
Using a query set, a database query will occur the first time it is used, and then Django will cache the results, and use the cached data when using this query set again, reducing the number of database queries.
Case 1: Every query interacts with the database, which increases the load on the database
for i in hero.object.all():
print(i.name)
for i in hero.object.all():
print(i.name)
Case 2: After storage, the query set can be reused, and the data in the cache can be used for the second time
heros = heroinfo.object.all()
for i in heros:
print(i.name)
for i in heros:
print(i.name)