时间:2021-07-01 10:21:17 帮助过:12人阅读
1 class UserInfo(models.Model): 2 username = models.CharField(max_length=32) 3 password = models.CharField(max_length=32) 4 age = models.IntegerField()
2、在全局配置中添加APP名
3、通过类创建表
A、python manage.py makemigrations
执行完后会在APP下生成一个py文件,如下图:
B、python manage.py migrate
执行完之后会在数据库中创建一个表,如下图:
4、配置路由并调试通过
5、views下数据库操作--增删改和查
1 from openstack import models 2 def db_handle(request): 3 #增加 4 # models.UserInfo.objects.create(username="han",password="123",age=30 ) 5 # data = {"username":"kai","password":"1234","age":30,} 6 # models.UserInfo.objects.create( **data) 7 # return HttpResponse("tianjia ok") 8 9 #删除 10 # models.UserInfo.objects.filter(username="han").delete() 11 # return HttpResponse("shanchu ok") 12 13 #修改 14 # models.UserInfo.objects.all().update(age=18) 15 # return HttpResponse("xiugai ok")
1 #查询 2 # models.UserInfo.objects.all() #获取所有数据 3 # models.UserInfo.objects.filter(age=18) #获取age=18的所有数据 4 # models.UserInfo.objects.filter(age=18).first() #获取age=18的第一个数据 5 user_list_obj = models.UserInfo.objects.all() 6 for line in user_list_obj: 7 print(line.username,line.password,line.age) 8 return HttpResponse("ok") #页面显示为ok
6、返回html页面数据展示
A 首先创建一个模板
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form action="/db_handle/" method="post"> 9 <p><input type="text" name="username"/></p> 10 <p><input type="text" name="password"/></p> 11 <p><input type="text" name="age"/></p> 12 <p><input type="submit" value="提交"/></p> 13 </form> 14 <table border="1"> 15 <thead> 16 <tr> 17 <th>username</th> 18 <th>password</th> 19 <th>age</th> 20 </tr> 21 </thead> 22 <tbody> 23 {% for item in li %} 24 <tr> 25 <td>{{ item.username }}</td> 26 <td>{{ item.password }}</td> 27 <td>{{ item.age }}</td> 28 </tr> 29 {% endfor %} 30 </tbody> 31 </table> 32 </body> 33 </html>
B 在APP views中编写查询数据函数
1 from openstack import models 2 def db_handle(request): 3 user_list_obj = models.UserInfo.objects.all() 4 return render(request,‘t1.html‘,{‘li‘:user_list_obj})
Django基础之数据库增删改查
标签:meta manage first user order orm 通过 页面 item