欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django对数据库的增删改查代码示例

程序员文章站 2022-05-07 12:43:57
...

(1)添加数据:

第一种方法:

#用户添加(1)
def user_add(request):    
    if request.method == "POST":
        user_views.objects.create(username= request.POST['username'])
        user_views.objects.create(is_superuser = request.POST['is_superuser'])
        user_views.objects.create(request.POST['canteen_admin'])
        user_views.objects.create(request.POST['tel_num'])
        user_views.objects.create(request.POST['wechat_num'])
        user_views.objects.create(request.POST['dep_id'])
        user_views.objects.create(request.POST['name'])
        #ticketfood_data = json.dumps(ticketfood_data)
        return HttpResponse('200')
    else:
        return HttpResponse('500')

第二种方法:

#用户添加
def user_add(request):    
    if request.method == "POST":
        user_add = user_views()
        user_add.username = request.POST['username']
        user_add.is_superuser = request.POST['is_superuser']
        user_add.canteen_admin = request.POST['canteen_admin']
        user_add.tel_num = request.POST['tel_num']
        user_add.wechat_num = request.POST['wechat_num']
        user_add.dep_id = request.POST['dep_id']
        user_add.name = request.POST['name']
        user_add.save()
        #ticketfood_data = json.dumps(ticketfood_data)
        return HttpResponse('200')
    else:
        return HttpResponse('500')

(2)删除数据:

#用户删除
def user_del(request):    
    if request.method == "POST":
       username = request.POST['username']
       user_views.objects.filter(username=username).delete()
       return HttpResponse('200')
    else:
       return HttpResponse('500')

(3)修改数据

def user_update(request):    
    if request.method == "POST":
       username = request.POST['username']
       user_views.objects.filter(username=username).update(tel_num=request.POST['tel_num'])
       user_views.objects.filter(username=username).update(wechat_num=request.POST['wechat_num'])
       user_views.objects.filter(username=username).update(dep_id=request.POST['dep_id'])
       user_views.objects.filter(username=username).update(name=request.POST['name'])
       #ticketfood_data = json.dumps(ticketfood_data)
       return HttpResponse('200')
    else:
       return HttpResponse('500')

(4)查找数据

#用户显示
def user_data(request):
    if request.method == "GET":
        user_obj = user_views.objects.all()
        
        for user in user_obj:
            user_data = []
            dic_data = {'username':user.username,'is_superuser':user.is_superuser,'canteen_admin':user.canteen_admin,'tel_num':user.tel_num,'wechat_num':user.wechat_num,'dep_id':user.dep_id,'dep_name':user.dep_name,'name':user.name}
            user_data.append(dic_data)
        user_data = json.dumps(user_data)
        return HttpResponse(user_data)
    else:
        return HttpResponse('user is null!')

 

相关标签: Python