Django中实现简单的CRUD
作者:互联网
# models.py
class User(models.Model):
id = models.IntegerField(primary_key=True)
username = models.CharField(max_length=32, unique=True)
# views.py
@require_GET
def get_user_list(request):
users = User.objects.all()
data = [{'id': user.id, 'username': user.username} for user in users]
return JsonResponse({'code': 200, 'data': data, 'message': '查询成功'})
@require_GET
def add_user(request):
request.encoding = 'utf-8'
if request.GET:
username = request.GET['username']
id = request.GET['id']
if username and id:
User.objects.create(id=id, username=username)
return JsonResponse({'code': 200, 'msg': '添加成功'})
else:
return HttpResponse('请传入username和id')
else:
return HttpResponse('请求方式错误')
@require_GET
def delete_user(request):
request.encoding = 'utf-8'
if request.GET:
id = request.GET['id']
if username:
User.objects.filter(id=id).delete()
return JsonResponse({'code': 200, 'msg': '删除成功'})
else:
return HttpResponse('请传入id')
else:
return HttpResponse('请求方式错误')
@require_GET
def update_use(request):
request.encoding = 'utf-8'
if request.GET:
id = request.GET['id']
username = request.GET['username']
if username and id:
User.objects.filter(id=id).update(username=username)
return JsonResponse({'code': 200, 'msg': '修改成功'})
else:
return HttpResponse('请传入username和id')
else:
return HttpResponse('请求方式错误')
标签:username,return,GET,CRUD,request,Django,简单,HttpResponse,id 来源: https://www.cnblogs.com/huturen/p/15504767.html