Django built serializers (json string into the target sequence
from django.core import serializers def test(request): book_list = Book.objects.all() ret = serializers.serialize("json", book_list) return HttpResponse(ret)
Two rest-framework sequence of the Serializer
models section
from django.db import models # Create your models here. class Book(models.Model): title=models.CharField(max_length=32) price=models.IntegerField() pub_date=models.DateField() publish=models.ForeignKey("Publish") authors=models.ManyToManyField("Author") def __str__(self): return self.title class Publish(models.Model): name=models.CharField(max_length=32) email=models.EmailField() def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def __str__(self): return self.name
section view
from rest_framework.views import APIView from rest_framework.response import Response from .models import * from django.shortcuts import HttpResponse from django.core import serializers from rest_framework import serializers class BookSerializers(serializers.Serializer): title=serializers.CharField(max_length=32) #title3=serializers.CharField(source='title') #Specifies source = 'title', title field indicates the sequence of the model table, the life of the same name TITLE3 (title and source = 'title' specified name must be unique) . Price = serializers.IntegerField () pub_date = serializers.DateField ( ) publish = serializers.CharField (Source = " publish.name " ) # Source can not only specify a field, you can also specify a method, if the method, the method will execute without brackets # in the authors = serializers.CharField (Source = " authors.all ") # details of the sequence of the publishing house, after a specified SerializerMethodField, may correspond to a method, return what, publish_detail is what in the authors = serializers.SerializerMethodField (READ_ONLY = True) # WRITE_ONLY sequence of the time, the field does not display # #read_only deserialization time, the field does not pass # # Get_ wording corresponding method of securing field name DEF get_authors (Self, obj): TEMP = [] for author in obj.authors.all (): temp.append (author.name) return TEMP # here may continue to use the author the Serializers, # DEF get_authors (Self, obj): # method a: # return [{ 'name': author.name, 'Age':} for author.age author in obj.authors.all ()] # method II : # RET = obj.authors.all () # SS = AuthorSerializer (RET, MANY = True) # return ss.data
# need to rewrite Crete methods
def create (self, validated_data):
res = models.Book.objects.create(**validated_data)
return authorser.data
class BookViewSet(APIView): def get(self,request,*args,**kwargs): book_list=Book.objects.all() # 序列化方式1: # 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("ok") # 序列化方式2: # data=serializers.serialize("json",book_list) #HttpResponse return (the Data) # serialization 3: bs = BookSerializers (Initial = book_list, MANY = True) # MANY = True on behalf of a number of data, if only one data (you can not write), many = False (or may not. write) .Instance serialized object is to return the Response (bs.data) # serialization. 4: # RET = models.Book.objects.all () values ( 'NID', 'title'). # dd = List (RET) # return the HttpResponse (json.dumps (dd)) # using inheritance Serializers serialized object class, deserialization DEF POST (Self, Request): # # example of generating a sequence of objects of the class, data is dictionary to deserialize # # Print (request.data) bookser = BookSerializers (Data = request.data) IFbookser.is_valid (): # # data cleaned by the RET = bookser.create (bookser.validated_data) # return the Response ()
A method as defined in the model, may be directly performed in the specified source:
class UserInfo(models.Model): user_type_choices = ( (1,'普通用户'), (2,'VIP'), (3,'SVIP'), ) user_type = models.IntegerField(choices=user_type_choices) username = models.CharField(max_length=32,unique=True) password = models.CharField(max_length=64) #视图 ret=models.UserInfo.objects.filter(pk=1).first() aa=ret.get_user_type_display() #serializer xx=serializers.CharField(source='get_user_type_display')
The sequence of the rest-framework ModelSerializer
from rest_framework import serializers from rest_framework.response import Response from app01 import models class AuthorSerializer(serializers.Serializer): name=serializers.CharField() age=serializers.CharField() class BookSerializers(serializers.ModelSerializer): class Meta: model = models.Book #展示全部 # fields = "__all__" #可以允许展示的 fields=['nid' , ' Title ' , ' in the authors ' , ' publish ' ] # does not allow the # the exclude = ( 'NID',) # can not be used simultaneously with the fields # depth = 1 # depth control, write a few layers to get inside, more layers, the slower the response, the official suggested between 0-10, most personal recommendations layer 3 # XX = serializers.CharField (Source = 'get_xx_display') publish = serializers.SerializerMethodField () DEF get_publish (Self, obj) : return obj.publish.name # this approach to the field at home late in the authors = serializers.SerializerMethodField () DEF get_authors (Self, obj): RET =obj.authors.all () SS = AuthorSerializer (RET = Initial, MANY = True) return ss.data # Using inheritance ModelSerializers serialized object class, deserialization
DEF POST (Self, Request): # Example yielded serialization of an object class, data is deserialized dictionary bookser = BookSerializers (data = request.data) # bookser.data IF bookser.is_valid (raise_exception = True): # washed data via bookser.save () the else : Print (bookser.errors [ ' name ' ] [0]) return Response()
And saving data check request serialization assembly of five
class BookSerializer1 (serializers.Serializer): title = serializers.CharField (error_messages, = { ' required ' : ' title can not be empty ' }) # this way to be saved, must override the create method
Check field of view by left hook function Source:
# Deserialization check (check local, global parity) # use of hooks are generally written field, rather than __all__ method DEF validate_name (Self, value): Print (value) The raise exceptions.ValidationError ( ' can not begin SB ' ) # IF value.startswith ( 'SB'): # The raise the ValidationError ( 'can not start SB') # return value DEF the validate (Self, attrs): Print (attrs) # IF attrs.get ( 'price') = attrs.get ( 'XX'):! # The raise exceptions.ValidationError ( 'name and price equal to abnormal') return attrs
view view
DEF POST (Self, Request): # Example of a sequence of objects generated class, data is deserialized dictionary bookser = BookSerializer (Data = request.data) # bookser.data # raise_seception Error = True displayed to the front end IF bookser.is_valid (raise_exception = True): # washed data via bookser.save () the else : Print (bookser.errors [ ' name ' ] [0]) return the Response ()
Analysis of the sequence of source assembly
Serialization component, first call __new__ method, if = MANY True, the object generation ListSerializer, if False, to generate the object Serializer sequence object .data method - data call the parent class method --- calling the object's own to_representation (from sequence no such methods defined class, to find a parent class) Aerializer to_representation class has a method, for loop execution attribute = field.get_attribute (instance) again went get_attribute Field class method, self.source_attrs is to be sliced Source, then perform get_attribute method, source_attrs when a parameter passed in the past, is the determination method performed on the brackets, put the attribute value is taken out
Book of additions and deletions to change search resful Interface:
View layer:
class BookSerializers(serializers.ModelSerializer): class Meta: model=models.Book fields='__all__' class BookView(APIView): def get(self, request): book_list = models.Book.objects.all() bs = BookSerializers(book_list, many=True) # 序列化数据 return Response(bs.data) def post(self, request): # 添加一条数据 print(request.data) bs=BookSerializers(data=request.data) if bs.is_valid(): bs.save() # 生成记录 return Response(bs.data) else: return Response(bs.errors) class BookDetailView(APIView): def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data) def put(self,request,pk): book_obj = models.Book.objects.filter(pk=pk).first() bs=BookSerializers(data=request.data,instance=book_obj) if bs.is_valid(): bs.save() # update return Response(bs.data) else: return Response(bs.errors) def delete(self,request,pk): models.Book.objects.filter(pk=pk).delete() return Response("")
routing:
url(r'^books/$', views.BookView.as_view()), url(r'^books/(?P<pk>\d+)$', views.BookDetailView.as_view()),