标签:ict work man sage 成功 ret pos json格式 port
1、json模块: 不支持序列化queryset和object对象
from django.shortcuts import render, HttpResponse from app01 import models from django import views import json class BookView(views.View): # json 不支持序列化queryset和object对象 def get(self, request): book_list = models.Book.objects.all().values(‘pk‘, ‘title‘, ‘price‘) book_list_json = json.dumps(list(book_list)) return HttpResponse(book_list_json) # from django.forms.models import model_to_dict # import json # data=[] # for obj in book_list: # data.append(model_to_dict(obj)) # print(data) # return HttpResponse(json.dumps(data))
2、django内置serializers:支持将queryset对象转换成json格式
from django.shortcuts import render, HttpResponse from django.core import serializers from app01 import models from django import views class BookView(views.View): # django自带的序列化组件serializers def get(self, request): book_list = models.Book.objects.all() book_list_json = serializers.serialize(‘json‘, book_list) # (‘格式‘, queryset) return HttpResponse(book_list_json)
3、rest_framework的serializers:支持将queryset对象转换成json格式,且支持object对象。更方便的更新数据库
from django.shortcuts import render, HttpResponse from rest_framework import serializers from app01 import models from django import views class BookSerializers(serializers.ModelSerializer): # authors = AuthorsSerializers(many=True) class Meta: model = models.Book # fields = ["title", "price", "publish_id", "pub_date", "authors"] fields = "__all__" extra_kwargs = { ‘title‘: {"error_messages": {"required": "书名内容不能为空"}}, ‘publish‘: {"error_messages": {"required": ‘出版社不能为空‘}}, ‘price‘: {"error_messages": {"required": ‘价格不能为空‘}} } depth = 1 # 获取表中的多对多字段深度 class BookView(APIView): def get(self, request): Book_list = models.Book.objects.all() ser = BookSerializers(Book_list, many=True) # queryset对象many=True,object对象默认为False ser = ser.data # data取出序列化后的数据 # print(ser, type(ser)) # return Response(ser) # 继承REST framework下的APIview才能使用,响应器自动处理OrderedDict
return HttpResponse(ser) #OrderedDict
提交post请求:将post数据交给序列化类,判断后save即可(django原生View下的post只能取form-data数据,rest_framework的APIView下,用request.data取post数据,且能取到其它原生格式,json等)。如果序列化类设置depth深度后,post请求时,数据容易更新失败。
def post(self, request): ser = BookSerializers(data=request.data) if ser.is_valid(): ser.save() return HttpResponse(json.dumps(ser.data)) else: print(ser.errors) return HttpResponse(json.dumps(ser.errors))
重写save中的create和update方法:save方法实际是判断数据是否已经存在后,默认调用ModelSerializer类下的create或者update方法,我们可以在自己的序列化类中覆盖它们
class BookSerializers(serializers.ModelSerializer): class Meta: model=Book fields="__all__" # exclude = [‘authors‘,] # depth=1 def create(self, validated_data): authors = validated_data.pop(‘authors‘) obj = Book.objects.create(**validated_data) obj.authors.add(*authors) return obj
单条数据的get、put和delete请求:
class BookDetailView(APIView): def get(self, request, id): book_obj = models.Book.objects.filter(pk=id).first() ser = BookSerializers(book_obj) data = ser.data return Response(data) def put(self, request, id): book_obj = models.Book.objects.filter(pk=id).first() ser = BookSerializers(book_obj, data=request.data) if ser.is_valid(): ser.save() return Response(ser.data) else: return Response(ser.errors) def delete(self, request, id): models.Book.objects.filter(pk=id).delete() return Response(‘删除成功‘)
一:几种序列化方式与rest_framework视图的初级使用
标签:ict work man sage 成功 ret pos json格式 port
原文地址:https://www.cnblogs.com/aizhinong/p/12541920.html