ORM:对象关系映射
作用:让不熟悉sql语句的人也能操作数据库
不足之处:封装程度太高,有时候sql语句效率偏低,需要手动书写sql语句
类————>表
对象————>记录
对象.属性—————>字段对应的值
models.py
1.在model.py中定义一个类
class User(models.Model):id = models.AutoField(primary_key=True)name = models.CharField(max_length=32) """ CharField必须制定max_length"""password = models.IntegerField()
2.数据库迁移命令(重点)
python3 manage.py makemigrations 将操作记录到migrations文件夹下
python3 manage.py migrate 将操作同步到数据库中
只要修改了models.py中和数据库有关的代码 则需要重新执行上述两条命令
字段的增删改查
增加
1.直接在终端内给默认值
2.允许该字段可以为空 null=True
3.直接给字段设置默认值 default=值
修改
直接修改代码然后执行两个命令
删除
注释代码后执行两个命令
(执行后原来的数据都没了)
数据
查询
res = models.user.objects.filter(username=username)
列表套数据对象,支持索引取值等,但不支持负数
不推荐索引取值,推荐使用.first()
filter可以携带多个参数,参数与参数之前是and关系,可以将filter想成where
增加
res=models.user.objects.create(username=username,password=password)
或
reg_obj=models.user(username=username,password=password)
reg_obj.save()
django多表关系创建(小白版)
from django.db import models#请不要在乎类名,学习笔记我懒,不用驼峰式命名# Create your models here.class book(models.Model):title = models.CharField(max_length=32)price = models.DecimalField(decimal_places=2, max_digits=8) # 小数总共8位,小数点后两位publish = models.ForeignKey(to='pulish')authors = models.ManyToManyField(to='author')#该字段是虚拟字段,是告诉orm是多对多关系class pulish(models.Model):name = models.CharField(max_length=32)addr = models.CharField(max_length=32)class author(models.Model):authorname = models.CharField(max_length=32)age = models.IntegerField()author_detail = models.OneToOneField(to='authordetail')class authordetail(models.Model):phone = models.BigIntegerField()addr = models.CharField(max_length=32)#多对多关系表中不需要像mysql一样新建第三张表,外键字段在任意一方都可以,推荐建立在查询频率较高的一方#一对一关系表中外键字段可以在任意一方,推荐建立在查询频率较高的一方#在django1.x中外键默认是级联更新和删除#记得运行makemigrations和migrate哦!
