(1)goods APP下新建serializers.py文件:
# -*- coding: utf-8 -*-
from rest_framework import serializers
继承Modelserializer简单的写法
class GoodsSerializer(serializers.Modelserializer):
classMeta:
model= Goods
fields = ('name', 'click_num', 'goods_front_image')
//将上述字段,添加到数据库函数
def create(self, Validated_data):
return Goods.objects.create(**validated_data)
(2)goods APP下views.py文件:
# -*- coding: utf-8 -*-
from .serializers import GoodsSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Goods
class GoodsListView(APIView):
// 接收前端传来的数据,保存在data里; serializer.save()调用serializers.py里的create()函数保存数据
def post(self, request, format=None):
serializer = GoodsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serialize.data, status=status.HTTP_201_CREATED)
return Response(serialize.error, status=status.HTTP_400_BAD_REQUEST)
接收前端传来的数据, serializer.save()调用serializers.py里的create()函数保存数据
于 2018-07-06 13:47:27 首次发布