Django学习——数据库的迁移和增删改查
一、迁移
将模型类同步到数据库中。
1.1 生成迁移文件
python manage.py makemigrations [app名]
1.2 同步到数据库中
python manage.py migrate
二、增删改查
1. shell工具
Django的manage工具提供了shell命令,帮助我们配置好当前工程的运行环境(如连接好数据库等),以便可以直接在终端中执行测试python语句。
1.1通过如下命令进入shell
python manage.py shell
1.2导入模型类,以便后续使用
from booktest.models import BookInfo, HeroInfo
2.新建一个对象的方法有以下几种:
①Person.objects.create(name=name,age=age)
②p = Person(name="WZ", age=23)
p.save()
③p = Person(name="TWZ")
p.age = 23
p.save()
3.查询
1.Questiion.objects.all() objects定义表的类具备的默认属性
等价sql: cursor.exe(select * from question;) cursor.fetchall()
2.Question.objects.filter(id=1,text=‘吃饭了吗?’) 相当于where条件,返回列表。
sql: select * from question where id = 1 and text=’’;
3.Question.object.filter(question_text__startswith=‘今天’).order(-id) 大于小于,特殊sql概念通过字段后双下划线
sql:select * from question where question_text like ‘今天%’
4.Question.objects.get(id=1) 只取一条数据
sql:select * from table where id=1; cursor.fetch_one()
5.Question.objects.raw(‘selct…’) 执行原生sql语法
6.表连接 join
一对多:学生表,班级表,一个班多个学生.班级是1的一方,学生表是多的一方。
sql :(1)select id from question;select * from choice where question_id=%s;
(2) select * from question as q join choice c on q.id=c.question_id=%s;
orm:
(1) q = Question.objects.get(text=‘今天’) id=q.id Choice.objects.filter(question_id=id)
(2)q.choice_set.all 从一的一方取外键关联的结果集
4.修改
q =Question.objects.get(id=1)
q.text = ‘新值’
q.save()
相当于sql:update table set text=‘新值’ where id=1;commit;
5.删除
q = Question.objcts.get(id=1)
q.delete()