table of Contents
The django orm (Model model)
Model (model) steps created:
1. The need to create a database
2. The configuration information in the database connection settings:
3. __init__ following documents in the corresponding app:
Import pymysql
pymysql.install_as_MySQLdb ()
4 corresponds to the required settings in the INSTALL_APPS app will be added to it
orm basic CRUD
1. Create a table
A class corresponding to a table, such as a new user class key, can use inheritance django new key to the models.Model
Field is set to correspond to the object, such as id can be increased by shaping from models.AutoField setting type, name may be set by the type varchar models.CharFeild.
Then converted to an actual table type, by two command
python manage.py makemigrations ### 生成迁移文件
python manage.py migrate ### 生成实际的表
2. CRUD
Single table:
Inquire
models.UserInfo.objects.all()
#<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
models.UserInfo.objects.values("name", 'age')
#<QuerySet [{'name': 'wdr', 'age': '18'}, {'name': 'sima', 'age': '16'}]>
models.UserInfo.objects.values_list('name','age')
#<QuerySet [('wdr', '18'), ('sima', '16')]>
models.UserInfo.objects.first()
#查询到的第一个对象UserInfo: UserInfo object
models.UserInfo.objects.filter(id=1).first()
#用filter加条件进行筛选查询,若想要查询id>3的可以通过id__gt=3来设置便可,如果不加条件相当于all()
increase
models.UserInfo.objects.create(name='wjk',age='19',ut_id=1)
#或者用可变长形参形式将字典打散为关键字传入方式写入
delete
models.UserInfo.objects.filter(id=4).delete()
Update
models.UserInfo.objects.filter(id=3).update(name='yyqx')
Even many operating table:
Forward inquiry
res=models.UserInfo.objects.all()
for obj in res:
print(obj.name,obj.age,obj.ut.title)
#### 神奇双下划线
models.UserInfo.objects.values('name', 'age', 'ut__title')
models.UserInfo.objects.values_list('username', 'age', 'ut__title')
Reverse Lookup
res = models.UserType.objects.first()
obj = res.userinfo_set.first()
# 通过表名小写_set反向查询这个表内信息
用表名小写__字段名
models.UserType.objects.values("title", 'userinfo__id', 'userinfo__age', 'userinfo__name')