Django学习笔记之View操作指南
作者:三省吾身 发布时间:2023-05-29 14:08:47
Django的View
一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应。响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片。
无论视图本身包含什么逻辑,都要返回响应。代码写在哪里也无所谓,只要它在你当前项目目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,大家约定成俗将视图放置在项目(project)或应用程序(app)目录中的名为views.py的文件中。
导入: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
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)
上述的操作只能适用于数据表中字段很少的情况,如果字段较多,写起来会很麻烦,不利于开发
总结
来源:https://segmentfault.com/a/1190000039646191


猜你喜欢
- 本文首先介绍了Python中的模块的概念,谈到了一个模块往往由多个模块组成,然后通过具体实例,分析了模块重载的相关内容,具体介绍如下。模块是
- 第一题:ASP中,VBScript的唯一的数据类型是什么?第二题:在ASP中,VBScript有多种控制程序流程语句,如If…Then, S
- 建立连接在WPF当中,需要为View与ViewModel建立连接, 我们需要找到View的DataContext, 如下所示:建立连接的方式
- 在python中有不少对于集合迭代的方法,我们把程序运行后的再一次循环叫做迭代,每一次都循环都可以看做是一次迭代。那么在迭代结束后,我们需要
- __author__ = 'clownfish'#coding:utf-8import urllib2,urllib,coo
- 本文需要一点Python socket基础。回顾RPC客户端(Client):服务调用方。客户端存根(Client Stub):存放服务端地
- 经过漫长的等待,近日,微软终于发布了Silverlight 2正式版的发布不仅让微软有了更多和Flash叫板的机会,同时也将RIA(Rich
- 关于Jmeter性能测试工具不再过多介绍。如果你要学习软件性能测试,那么多少应该会对它有所耳闻。强烈建议阅读官方文档学习:http://jm
- 目录一、对比数据类型二、可变集合构造方法三、不可变集合的构造方法四、集合构造注意事项 Python集合又是一种新的数据类型,集合有
- 使用PyTorch进行训练和测试时一定注意要把实例化的model指定train/eval,eval()时,框架会自动把BN和DropOut固
- 写程序的人在编写由asp页面生成静态页面html的时候,如果同时生成大量页面,一定遇到过浏览器下方的进度条上显示着3%,6%,10%等缓慢增
- 作为一种常见的数据结构,缓冲区(Buffer)在计算机科学中有着广泛的应用。Go 语言标准库中提供了一个名为 bytes.Buffer 的缓
- 一,利用键盘响应,在不刷新本页面的情况下验证表单输入是否合法用户通过onkeydown和onkeyup事件来触发响应事件。使用方法和oncl
- PHP hebrev() 函数实例反向显示希伯来字符:<?php echo hebrev("á çù&
- 本文实例讲述了Python变量、数据类型、数据类型转换相关函数用法。分享给大家供大家参考,具体如下:python变量的使用不需要进行类型声明
- (1)设计一个算法,确定两个矩形是否相交(即有重叠区域) (2)如果两个矩形相交,设计一个算法,求出相交的区域矩形 (1) 对于这个问题,一
- 想做个和IBM公司一样的网站LOGO,试了半天也没有做出来,郁闷之下,只好求高手帮助!先在这里谢谢了!方法一1、写上IBM,调节字号颜色2、
- PHP sessionphp session 反序列化漏洞存在的原因:当序列化session和读取反序列化字符时采用的序列化选择器不一样时,
- socket解析HTTP请求内容思路1. 解析HTTP请求的头部HTTP请求头部的结束符行为"\r\n",可以按行读取H
- 如果想读取用 open() 函数打开的文件中的内容,除了可以使用 read() 函数,还可以使用 readline() 和 readline