serializer用起来稍微麻烦,可以使用ModelSerializer,类似于django里的Form与ModelForm
1.定义ModelSerializer
from rest_framework import serializersfrom goods.models import Goods, GoodsCategory# class GoodsSerializer(serializers.Serializer):# """# Goods的serializer# """# name = serializers.CharField(required=True, max_length=100)# chick_num = serializers.IntegerField(default=0)# # goods_front_image = serializers.ImageField()# # 外键需要写数据里的字段名,不能写类里的字段名,例如不能写category,需要些category_id,请求时也得时数据库里的名# category_id = serializers.IntegerField()## """# 创建# """# def create(self, validated_data):# return Goods.objects.create(**validated_data)class CategorySerializer(serializers.ModelSerializer): class Meta: model = GoodsCategory fields = '__all__'# 优点:解决上面的category_id外键问题class GoodsSerializer(serializers.ModelSerializer): """ Goods的serializer """ # 自定义,可以获取到外键数据 # read_only表示只用在获取数据 category_obj = CategorySerializer(source='category',read_only=True) category_name = serializers.CharField(source='category.name',read_only=True) class Meta: model = Goods # 外键写类里的名就可以 # fields = ('name','chick_num','category') fields = '__all__'
2.View引用
from django.shortcuts import renderfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework import statusfrom rest_framework.parsers import JSONParserfrom goods.models import Goodsfrom goods.serializer import GoodsSerializerclass GoodsList(APIView): def get(self, request): goods = Goods.objects.all()[:10] goods_json = GoodsSerializer(goods, many=True) # print(type(goods_json)) # print(type(goods_json.data)) return Response(goods_json.data) def post(self, request): serializer = GoodsSerializer(data=request.data) # 不管是form或是json,post过来的数据,都可以通过request.data获取 if serializer.is_valid(): serializer.save() return Response({ 'data': 'ok'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
3.test