Django Learning Note View Operating Guide

  • 2021-10-13 08:16:30
  • OfStack

View of Django

A view function (class), or view for short, is a simple Python function (class) that accepts an Web request and returns an Web response. The response can be 1 HTML content for a Web page, 1 redirect, 1 404 error, 1 XML document, or 1 picture.

No matter what logic the view itself contains, the response should be returned. It doesn't matter where the code is written, as long as it is under your current project directory. There are no more requirements-it can be said that "there is no magic place". To put the code somewhere, it is customary to place the view in a file called views. py in the project (project) or application (app) directory.

Import: from django.views import View

1. Query all data

Query data defines get method in custom view class

Use JsonResponse in django. http module to return data in non-json format

The parameter safe=False must be added in JsonResponse, otherwise an error will be reported: In order to allow non-dict objects to be serialized set ES50safe


from django.http import HttpResponse 
from django import http 
# Create your views here. 
class UserView(View): 
 '''  User view  ''' 
 def get(self, request): 
  #  Model class instantiation object  
  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) 

Step 2 Create data

Use json in django to convert json data transmitted from the front end into a dictionary

Use Q in the django. db. models module to query whether multiple fields exist in the database


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): 
 '''  User view  ''' 
 def post(self, request): 
  #  Get data , json Transferring dictionary  
  dict_data = json.loads(request.body.decode()) 
  print(dict_data) 
  nick_name = dict_data.get('nickName') 
  code = dict_data.get('code') 
  open_id = "xljsafwjeilnvaiwogjirgnlg" 
  #  Check data  
  result = UserProfile.objects.filter(Q(code=code) | Q(open_id=open_id)) 
  if not result.exists(): 
   #  Data warehousing  
   user = UserProfile.objects.create( username=nick_name, open_id=open_id, code=code ) 
   #  Return response  
   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(" User already exists ", safe=False, status=202)

3. Query a certain piece of data (single)

The front end needs to pass pk/id value, and query data through pk/id. get must be used to query one piece of data, but filter cannot be used, otherwise an error will be reported: AttributeError: 'QuerySet' object has no attribute 'id'

Data conversion

Return response


class UserProfileDetail(View): 
 '''  Details view  ''' 
 def get(self, request): 
  userInfo = UserProfile.objects.get(id=id) 
  if not userInfo: 
   return HttpResponse(" Use of query Info Household does not exist ", 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) 

4. Update 1 piece of data

The front end needs to pass pk/id value, and query data through pk/id. get must be used to query one piece of data, but filter cannot be used, otherwise an error will be reported: AttributeError: 'QuerySet' object has no attribute 'id'

When updating a piece of data, you must use filter to query the data set, and then use update (**data) to update the data. You cannot use get, otherwise an error will be reported: AttributeError: 'Model Class' object has no attribute 'update'

The get query gets the data object, while the filter query gets the data set


class UserProfileDetail(View): 
 '''  Details view  ''' 
 def put(self, request, id): 
  data_dict = json.loads(request.body.decode()) 
  userInfo = UserProfile.objects.get(id=id) 
  if not userInfo: 
   return HttpResponse(" Use of query Info Household does not exist ", 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)

5. Delete a piece of data


class UserProfileDetail(View): 
 '''  Details view  ''' 
 def delete(self, request, id): 
  userInfo = UserProfile.objects.filter(id=id) 
  if not userInfo: 
   return HttpResponse(" Deleted data does not exist ", status=404)      
  UserProfile.objects.filter(id=id).delete() 
  return HttpResponse(" Data deletion succeeded ", status=204)

The above operation can only be applied to the case where there are few fields in the data table. If there are many fields, it will be very troublesome to write and is not conducive to development

Summarize


Related articles: