# 导包
from django.views import View
from django.http.response import JsonResponse
# 查询全部与添加数据
class UserList(View)
# 查询全部
def get(self,request)
user_list = User.objects.all()
data = [
{
"id":datas.id,
"name":datas.name,
"classroom":datas.classroom
}
for datas in user_list
]
return JsonResponse(data,safe=False)
#添加数据
def post(View):
id = request.POST.get("id")
name = request.POST.get("name")
classroom = request.POST.get("classroom")
if not all([ id,name,classroom]):
return JsonResponse( { ' msg ' : ' 缺少参数 ' }, status=400)
try:
User.objects.create( id=id, name=name,classroom=classroom )
except Exception as e:
return JsonResponse( { "msg" : "添加失败" }, statue=204 )
return JsonResponse({ "msg" : "添加成功" }, statue=200 )
#查询详情,更新数据,删除数据
class UserData(View):
#查询详情
def get(self,rquest,pk):
try :
user = User.objects.get( id=pk )
except User.DoesNotExist :
return JsonResponse({ 'msg' : '不存在' }, status=404 )
data = {
"id" : user.id,
"name" : user.name,
"classroom" : user.classroom
}
return JsonResponse( data )
#更新数据
def post(self,request,pk):
try :
user = User.objects.get( id=pk )
except User.DoesNotExist :
return JsonResponse({ 'msg' : '不存在' }, status=404 )
id = request.POST.get( 'id',user.id )
name = request.POST.get( 'name',user.name )
classroom = request.POST.get( 'classroom',user.classroom )
User.objects.filter( id=pk ).update( id=id, name=name, classroom=classroom )
return JsonResponse( { "msg" : "更新成功" }, status=200)
#删除数据
def delete(View):
User.objects.filter( id=pk ).delete()
return JsonResponse( { 'msg' : '删除成功‘ },status=200 )