FBV(function base views) 就是在視圖裏使用函數處理請求。html
看代碼:django
urls.pyapi
from django.conf.urls import url, include # from django.contrib import admin from mytest import views urlpatterns = [ # url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘, views.index), ]
views.py框架
from django.shortcuts import render def index(req): if req.method == ‘POST‘: print(‘method is :‘ + req.method) elif req.method == ‘GET‘: print(‘method is :‘ + req.method) return render(req, ‘index.html‘) 注意此處定義的是函數【def index(req):】
index.html函數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <form action="" method="post"> <input type="text" name="A" /> <input type="submit" name="b" value="提交" /> </form> </body> </html>
上面就是FBV的使用。post
CBV(class base views) 就是在視圖裏使用類處理請求。url
將上述代碼中的urls.py 修改成以下:code
from mytest import views urlpatterns = [ # url(r‘^index/‘, views.index), url(r‘^index/‘, views.Index.as_view()), ]
注:url(r‘^index/‘, views.Index.as_view()), 是固定用法。orm
將上述代碼中的views.py 修改成以下:xml
from django.views import View class Index(View): def get(self, req): print(‘method is :‘ + req.method) return render(req, ‘index.html‘) def post(self, req): print(‘method is :‘ + req.method) return render(req, ‘index.html‘)
注:類要繼承 View ,類中函數名必須小寫。
django的序列化框架提供了一個把django對象轉換成其餘格式的機制,一般這些其餘的格式都是基於文本的而且用於經過一個管道發送django對象,但一個序列器是可能處理任何一個格式的(基於文本或者不是)
django的序列化類位於django.core下面的serializers文件夾裏面,base.py文件裏面定義了序列器和反序列器的基類以及一些異常,init.py文件定義瞭如何根據格式來選擇對應的序列器等內容,咱們一塊兒來看看吧
init.py和base.py文件的函數原型以下圖
def serialize(format, queryset, **options): """Serialize a queryset (or any iterator that returns database objects) using a certain serializer.""" s = get_serializer(format)() s.serialize(queryset, **options) return s.getvalue() class Serializer(object): """ Abstract serializer base class. """ # Indicates if the implemented serializer is only available for # internal Django use. internal_use_only = False def serialize(self, queryset, **options):
那下面咱們開始正式講解django的序列化操做了
序列化數據 在最高層的api,序列化數據是很是容易的操做,看上面的函數可知,serialize函數接受一個格式和queryset,返回序列化後的數據:
簡單的寫法:
from django.core import serializers data = serializers.serialize("xml", SomeModel.objects.all())
複雜的寫法:
XMLSerializer = serializers.get_serializer("xml") xml_serializer = XMLSerializer() xml_serializer.serialize(queryset) data = xml_serializer.getvalue()