Django View 视图开发实战:增删改查完整指南
本文详细介绍 Django 中 View 视图函数的定义与使用,涵盖查询、创建、更新和删除数据的完整流程。重点解析 JsonResponse 中 safe=False 参数的必要性,以及 get 与 filter 在单条数据查询中的区别与报错处理,帮助开发者避免常见陷阱,提升后端开发效率。
Django View 视图基础
视图函数(或类)是 Django 中处理 Web 请求并返回响应的核心组件。它是一个标准的 Python 函数或类,负责接收前端传来的 Web 请求,并生成相应的 Web 响应。响应内容可以是 HTML 网页、重定向指令、404 错误页面、XML 文档或图片等任意格式。
无论视图内部逻辑多么复杂,其最终目的都是返回一个响应。代码的具体存放位置没有硬性限制,只要位于当前项目目录内即可。业界约定俗成的做法是将视图代码放置在项目或应用目录下的 views.py 文件中,这种约定使得代码结构清晰且易于维护。
首先需要导入必要的模块:from django.views import View
一、查询所有数据
在自定义的视图类中,通过定义 get 方法来处理数据查询请求。该方法负责从数据库获取数据并返回给前端。
为了返回非字典格式的数据(如列表),需要使用 django.http 模块中的 JsonResponse。
在使用 JsonResponse 时,必须显式添加 safe=False 参数。如果不添加该参数,当尝试序列化非字典对象(如列表)时,Django 会抛出异常:In order to allow non-dict objects to be serialized set the safe=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 格式数据转换为 Python 字典对象,以便后续处理。
接着,利用 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 值。在查询单条特定数据时,必须使用 get 方法,严禁使用 filter。若错误地使用 filter,会返回 QuerySet 对象,进而导致报错:AttributeError: 'QuerySet' object has no attribute 'id'。
获取到数据对象后,需进行必要的数据转换,将模型实例转换为字典格式,以便序列化为 JSON 响应。
最后,将转换后的数据通过 JsonResponse 返回给前端,完成单次查询响应。
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 值。同样必须使用 get 方法获取具体数据对象,若使用 filter 会因 QuerySet 对象没有 'id' 属性而报错:AttributeError: 'QuerySet' object has no attribute 'id'。
在更新数据时,虽然获取对象可用 get,但执行批量更新操作时必须使用 filter 查询数据集,并调用 update(**data) 方法。如果直接对 get 获取的对象调用 update,会报错:AttributeError: '模型类' object has no attribute 'update'。
需明确区分:get 查询返回的是具体的数据对象实例,而 filter 查询返回的是包含零个或多个对象的数据集(QuerySet)。
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)
上述手动处理字段的方式仅适用于字段较少的情况。当数据表字段较多时,手动编写每个字段的转换逻辑会非常繁琐,不利于代码维护和开发效率。
总结
本文介绍了 Django View 的基本操作与常见陷阱。掌握 JsonResponse 的使用、get 与 filter 的区别以及数据转换技巧,能有效提升 Django 后端开发的规范性与效率。更多相关内容请参考本站往期文章或关注后续更新,感谢支持。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









