关于django:Django中的View操作

29次阅读

共计 2853 个字符,预计需要花费 8 分钟才能阅读完成。

导入:from django.views import View

一、查问所有数据

  • 查问数据在自定义的视图类中定义 get 办法
  • 应用 django.http 模块中的 JsonResponse 对非 json 格局的数据做返回解决
  • 在 JsonResponse 必须增加 safe=False 参数,否则会报错:In order to allow non-dict objects to be serialized set the safe parameter to False.
from django.http import HttpResponse 
from django import http  
# Create your views here. 
class UserView(View):  
    '''用户视图'''   
    def get(self, request): 
        # 模型类实例化对象 
        users = UserProfile.objects.all() 
        user_list = [] 
        for user in users: 
            user_dict = { 
                'id': user.id, 
                'username': user.username, 
                'password': user.password, 
                'open_id': user.open_id, 
                'code': user.code 
            } 
        user_list.append(user_dict)
     return http.JsonResponse(user_list) 

二、创立数据

  • 应用 django 中的 json,把前端传递过去的 json 数据转成字典
  • 应用 django.db.models 模块中的 Q 来查问多个字段在数据库中是否存在
from django.views import View 
from django.http import HttpResponse 
from django import http 
from django.db.models import Q 
import json  
class UserView(View):  
    '''用户视图''' 
    def post(self, request): 
        # 获取数据, json 转字典 
        dict_data = json.loads(request.body.decode()) 
        print(dict_data) 
        nick_name = dict_data.get('nickName') 
        code = dict_data.get('code') 
        open_id = "xljsafwjeilnvaiwogjirgnlg" 
        # 校验数据 
        result = UserProfile.objects.filter(Q(code=code) | Q(open_id=open_id)) 
        if not result.exists(): 
            # 数据入库 
            user = UserProfile.objects.create(username=nick_name, open_id=open_id, code=code) 
            # 返回响应 
            user_dict = { 
                'id': user.id, 
                'username': user.username, 
                'password': user.password, 
                'open_id': user.open_id, 
                'code': user.code 
            } 
            return http.JsonResponse(user_dict) 
        return http.JsonResponse("用户已存在", safe=False, status=202)

三、查问某一条数据 (单个)

  • 前端须要传递 pk/id 值,通过 pk/id 查问数据,查问一条数据必须用 get,不能用 filter,否则会报错:AttributeError: ‘QuerySet’ object has no attribute ‘id’
  • 数据转换
  • 返回响应
class UserProfileDetail(View):  
    '''详情视图'''   
    def get(self, request): 
        userInfo = UserProfile.objects.get(id=id) 
        if not userInfo: 
            return HttpResponse("查问的用 Info 户不存在", status=404)                 
        user_dict = { 
            'id': userInfo.id, 
            'username': userInfo.username, 
            'password': userInfo.password, 
            'open_id': userInfo.open_id, 
            'code': userInfo.code 
        } 
        return http.JsonResponse(user_dict, status=200) 

四、更新一条数据

  • 前端须要传递 pk/id 值,通过 pk/id 查问数据,查问一条数据必须用 get,不能用 filter,否则会报错:AttributeError: ‘QuerySet’ object has no attribute ‘id’
  • 更新一条数据时必须应用 filter 来查问数据集,再应用 update(**data) 来更新数据,不能应用 get,否则会报错:AttributeError: ‘ 模型类 ’ object has no attribute ‘update’

get 查问获取到的是数据对象,而 filter 查问获取到的是数据集

class UserProfileDetail(View):  
    '''详情视图'''   
    def put(self, request, id): 
        data_dict = json.loads(request.body.decode()) 
        userInfo = UserProfile.objects.get(id=id) 
        if not userInfo: 
            return HttpResponse("查问的用 Info 户不存在", status=404)                 
        UserProfile.objects.filter(id=id).update(**data_dict) 
        userInfo = UserProfile.objects.get(id=id) 
        user_dict = { 
            'id': userInfo.id, 
            'username': userInfo.username, 
            'password': userInfo.password, 
            'open_id': userInfo.open_id, 
            'code': userInfo.code 
        } 
        return http.JsonResponse(user_dict, status=200)

五、删除某一条数据

class UserProfileDetail(View):  
    '''详情视图'''   
    def delete(self, request, id): 
        userInfo = UserProfile.objects.filter(id=id) 
        if not userInfo: 
            return HttpResponse("删除的数据不存在", status=404)                     
        UserProfile.objects.filter(id=id).delete() 
        return HttpResponse("数据删除胜利", status=204)

上述的操作只能实用于数据表中字段很少的状况,如果字段较多,写起来会很麻烦,不利于开发

正文完
 0