Django学习笔记之View操作指南

 更新时间:2021年03月20日 12:24:14   作者:三省吾身  
这篇文章主要给大家介绍了关于Django学习笔记之View操作指南的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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)

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

总结

到此这篇关于Django学习笔记之View操作指南的文章就介绍到这了,更多相关Django View操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python 弧度与角度互转实例

    python 弧度与角度互转实例

    这篇文章主要介绍了python 弧度与角度互转实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Python中的多行注释文档编写风格汇总

    Python中的多行注释文档编写风格汇总

    在Python中利用多行注释编写小型的程序文档说明非常方便,而约定俗成的格式也多种多样,这里我们就进行一下最常见的Python中的多行注释文档编写风格汇总:
    2016-06-06
  • python实现DEM数据的阴影生成的方法

    python实现DEM数据的阴影生成的方法

    这篇文章主要介绍了python实现DEM数据的阴影生成的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Python爬虫中IP池的使用小结

    Python爬虫中IP池的使用小结

    在网络爬虫的世界中,IP池是一个关键的概念,它允许爬虫程序在请求网页时使用多个IP地址,从而降低被封禁的风险,提高爬虫的稳定性和效率,本文将深入探讨Python爬虫中IP池的使用,以及如何构建和维护一个可靠的IP池,感兴趣的朋友一起看看吧
    2024-01-01
  • Python嵌套函数与nonlocal使用详细介绍

    Python嵌套函数与nonlocal使用详细介绍

    这篇文章主要介绍了Python嵌套函数与nonlocal使用,nonlocal关键字与global关键字有点相似,可以对比着理解。nonlocal关键字只能作用域局部变量,且始终找离当前最近的上层局部作用域中的变量
    2022-09-09
  • 使用Python、TensorFlow和Keras来进行垃圾分类的操作方法

    使用Python、TensorFlow和Keras来进行垃圾分类的操作方法

    这篇文章主要介绍了如何使用Python、TensorFlow和Keras来进行垃圾分类,这个模型在测试集上可以达到约80%的准确率,可以作为一个基础模型进行后续的优化,需要的朋友可以参考下
    2023-05-05
  • PyQt5打开文件对话框QFileDialog实例代码

    PyQt5打开文件对话框QFileDialog实例代码

    这篇文章主要介绍了PyQt5打开文件对话框QFileDialog实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • python展开嵌套列表的多种方法

    python展开嵌套列表的多种方法

    本文主要介绍了python展开嵌套列表的多种方法,包括for循环、列表推导式和sum函数三种方法,具有一定的参考价值,感兴趣的可以了解一下
    2025-03-03
  • 深入解析Python中BeautifulSoup4的基础知识与实战应用

    深入解析Python中BeautifulSoup4的基础知识与实战应用

    BeautifulSoup4正是一款功能强大的解析器,能够轻松解析HTML和XML文档,本文将介绍BeautifulSoup4的基础知识,并通过实际代码示例进行演示,感兴趣的可以了解下
    2024-02-02
  • 深入剖析Python的爬虫框架Scrapy的结构与运作流程

    深入剖析Python的爬虫框架Scrapy的结构与运作流程

    这篇文章主要介绍了Python的爬虫框架Scrapy的结构与运作流程,并以一个实际的项目来讲解Scrapy的原理机制,十分推荐!需要的朋友可以参考下
    2016-01-01

最新评论