Rest framework - json 데이터로rest 배우기framework

20609 단어 Django
1. json 데이터 목록을 Django로 되돌려줍니다
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)

2. 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

좋은 웹페이지 즐겨찾기