时间:2021-07-01 10:21:17 帮助过:20人阅读
views.py 执行增删查改等的操作
def orm(request):
#向userinfo插入数据,有以下三种方式 # models.UserInfo.objects.create(username=‘root‘,password=‘123‘) # dic={‘username‘:‘emily‘,‘password‘:‘666‘} #向userinfo插入数据 # models.UserInfo.objects.create(**dic) # # obj=models.UserInfo(username=‘alex‘,password=‘123‘) #向userinfo插入数据 # obj.save() #查询: # result = models.UserInfo.objects.all() #查询全部
result = models.UserInfo.objects.filter(username=‘alex‘,password=‘123‘) #根据条件筛选,组成 and # result是QuerySet类型,形同[]列表 # [obj(id,user,password),obj(id,user,password),obj(id,user,password)] for row in result: print(row.id,row.username,row.password) print(result) #打印出每一列的内容 #删除 # models.UserInfo.objects.all().delete()#全部删除 # models.UserInfo.objects.filter(id=4).delete() #更新 # models.UserInfo.objects.all().update(password="5555")#全部更新 # models.UserInfo.objects.filter(id=3).update(password="5555") return HttpResponse(‘orm‘)
viwes.py 获取数据传数据
def user_detail(request, nid): obj = models.UserInfo.objects.filter(id=nid).first() return render(request, ‘user_detail.html‘,{‘obj‘:obj}) def user_del(request, nid): models.UserInfo.objects.filter(id=nid).delete() return redirect(‘/cmdb/user_info/‘) def user_edit(request, nid): if request.method =="GET": obj = models.UserInfo.objects.filter(id=nid).first() return render(request, ‘user_edit.html‘,{‘obj‘:obj}) elif request.method=="POST": nid = nid u = request.POST.get(‘username‘) p = request.POST.get(‘password‘) models.UserInfo.objects.filter(id=nid).update(username=u,password=p) return redirect(‘/cmdb/user_info/‘)
xxx.html
<ul> {% for row in user_list %} <li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a>| <span>{{ row.user_group.caption }}</span> <a href="/cmdb/userdel-{{ row.id }}/">|删除</a> <a href="/cmdb/useredit-{{ row.id }}/">|编辑</a> </li> {% endfor %} </ul>
DjangoORM操作数据库
标签:res 需要 password def 查询 turn none 删除 choice