2019-1-1 22:22:32
CBV:基于类的视图
# urls.py内
url(r'^index/',views.Order.as_view())
#注意:必须.as_view() 来调用
#views.py内
# 需要导入
from django.views import View
class Order(View):
def get(self,request):
# get方法运行此处
def post(self,request):
# post方法运行此处
FBV:基于函数视图
#views.py内
def Order(request):
if request.method=='GET':
# get运行
if request.method=='POST':
# post运行
serializers序列化
- 如果想把很多model转化成json格式可以直接这样写
from django.views.generic.base import View
from django.http import HttpResponse
from django.core import serializers
from goods.models import Goods
class GoodsListView(View):
def get(self, request):
# 取前十个good的model
goods = Goods.objects.all()[:10]
# 利用serializers的serialize直接把所有model转化成json格式
json_data = serializers.serialize('json', goods)
# 必须要标明返回的 content_type 是 application/json
return HttpResponse(json_data, content_type='application/json')
- 也可以用Django的 JsonResponse,直接返回Ptyhon字典、列表等(可以dump成json格式)的type
from django.views.generic.base import View
from django.http import JsonResponse
from django.forms.models import model_to_dict
from goods.models import Goods
class GoodsListView(View):
def get(self, request):
json_list = []
for good in goods:
json_data = model_to_dict(good)
json_list.append(json_data)
# 这里要把safe设置成False,否则会Django报错,可以点进去看JsonResponse源码
return JsonResponse(json_list, safe=False)
from django.views.generic.base import View
from django.http import HttpResponse
from django.core import serializers
from goods.models import Goods
class GoodsListView(View):
def get(self, request):
# 取前十个good的model
goods = Goods.objects.all()[:10]
# 利用serializers的serialize直接把所有model转化成json格式
json_data = serializers.serialize('json', goods)
# 必须要标明返回的 content_type 是 application/json
return HttpResponse(json_data, content_type='application/json')
from django.views.generic.base import View
from django.http import JsonResponse
from django.forms.models import model_to_dict
from goods.models import Goods
class GoodsListView(View):
def get(self, request):
json_list = []
for good in goods:
json_data = model_to_dict(good)
json_list.append(json_data)
# 这里要把safe设置成False,否则会Django报错,可以点进去看JsonResponse源码
return JsonResponse(json_list, safe=False)