Django学习3——数据库的迁移和增删改查(未完善)

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值