Rest framework——从一段json数据来学rest_framework

一、用 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")

			# 使用django自带序列化类
			from django.core import serializers
			json_data = serializers.serialize('json', product)
			return HttpResponse(json_data, content_type="application/json")
			
			# 使用 JsonResponse
			from django.http import JsonResponse
			json_data = json.loads(serializers.serialize('json', product))
			return JsonResponse(json_data, safe=False)

二、使用rest_framwork来返回json数据

# serializers.py
from rest_framework import serializers
from .models import Product

# s1 自定义字段序列化
class ProductSerializer(serializers.Serializer):
	id = serializers.IntegerField()
	name = serializers.CharField(required=True, max_length=100)

	# 重写create函数可以保存前端传的数据
	def create(self, validated_data):
		return Product.objects.create(**validated_data)
		
# s2 根据model来序列化字段(指定或全部)
# 或存在自定义字段 自定义字段将替换指定字段中的该字段
class ProductSerializer(serializers.ModelSerializer):
	class Meta:
		model = Product
		fields = ('id', 'name')
		# 序列化全部字段
		# fields = ("__all__")
		
# s3 序列化外键字段
# 若序列化类中存在外键字段,外键字段将自动序列化为外键id
class CategorySerializer(serializers.Serializer):
	id = serializers.IntegerField()
	name = serializers.CharField(required=True, max_length=100)


class ProductSerializer(serializers.ModelSerializer):
	# 将外键字段信息按 CategorySerializer 类序列化
	category = CategorySerializer()
	# 将外键字段序列化显示为外键中的某一字段
	#category = serializers.CharField('category.name')
	class Meta:
		model = Product
		fields = ('id', 'name')
		# 序列化全部字段
		# fields = ("__all__")
		
	
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import ProductSerializer
from .models import Product

# v1-s1:s2:s2
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)

# v2
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)
	
		
# v3
class ProductList(generics.ListAPIView):
	products = Product.objects.all()
	serializer_class = ProductSerializer


# v4-url viewset
from rest_framework import viewsets
class ProductList(mixins.ListModelMixin, viewsets.GenericViewSet):
	products = Product.objects.all()
	serializer_class = ProductSerializer	

#urls.py
from .views import ProductList
# u1
products = ProductList.as_view({
	'get': 'list',
	'post': 'create'
})
url (r'product/$', product, name='product')


#u2
from rest_framework.routers import DefaultRouter
# 这样写的好处是不用重复性的注册大量相似的url
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

你可能感兴趣的:(Django)