一、用 Django 来返回一段 json 数据列表
import json
from .models import Product
from django.http import HttpResponse
from django.views.generic.base import View
class ProductListView1(View):
def get(self, request):
"""
通过 django 的 view 实现
"""
json_list = []
products = Product.objects.all()
for product in products:
json_dict = {}
json_dict["id"] = product.id
json_dict["name"] = product.name
json_dict["category"] = product.category
json_list.append(json_dict)
return HttpResponse(json.dumps(json_list), content_type="application/json")
from django.forms.models import model_to_dict
for product in products:
json_dict = model_to_dict(product)
json_list.append(json_dict)
return HttpResponse(json.dumps(json_list), content_type="application/json")
from django.core import serializers
json_data = serializers.serialize('json', product)
return HttpResponse(json_data, content_type="application/json")
from django.http import JsonResponse
json_data = json.loads(serializers.serialize('json', product))
return JsonResponse(json_data, safe=False)
二、使用rest_framwork来返回json数据
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(required=True, max_length=100)
def create(self, validated_data):
return Product.objects.create(**validated_data)
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name')
class CategorySerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(required=True, max_length=100)
class ProductSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Product
fields = ('id', 'name')
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import ProductSerializer
from .models import Product
class ProductList(APIView):
def get(self,request,format=None):
products = Product.objects.all()
products_serializer = ProductSerializer(goods, many=True)
return Response(products_serializer.data)
def post(self,request,format=None):
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Respnse(serializer.errors, status=status.HTTP_400)
from rest_framework import mixins
from rest_framework import generics
class ProductList(mixins.ListModelMixin, generics.GenericAPIView):
products = Product.objects.all()
serializer_class = ProductSerializer
def get(self, request, *args, **kwgras):
return self.list(request, *args, **kwargs)
class ProductList(generics.ListAPIView):
products = Product.objects.all()
serializer_class = ProductSerializer
from rest_framework import viewsets
class ProductList(mixins.ListModelMixin, viewsets.GenericViewSet):
products = Product.objects.all()
serializer_class = ProductSerializer
from .views import ProductList
products = ProductList.as_view({
'get': 'list',
'post': 'create'
})
url (r'product/$', product, name='product')
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'product', ProductList)
url(r'^', include(router.urls))
# 继承关系
GenericViewSet(viewset) --rest_framework
GenericAPIView --rest_framework
APIView --rest_framework
View --django
一篇简单易懂的serializer使用文章
http://www.cnblogs.com/yuncong/p/10128987.html