- settings.py 文件中配置rest_framework
INSTALLED_APPS = ('rest_framework',)
- 建立序列化和反序列化模型类
from goods.models import Goods from rest_framework import serializers class TypeSerializers(serializers.ModelSerializer): class Meta: model = Types fields = '__all__' class GoodsSerializers(serializers.ModelSerializer): # 外键 #types = serializers.CharField(source="goods_type") #types = serializers.PrimaryKeyRelatedField(queryset=Types.objects.all(), label='类型') types = TypeSerializers(read_only=True) #获取模型中的choice值 types_name = serializers.CharField(source="get_goods_type_display") # 显示自定义字段 types_difund = serializers.SerializerMethodField() class Meta: model = Goods #fields = "__all__" fields = ['id', 'good_name', 'price', 'types', 'types_name', 'types_difund'] def get_types(self, row): type_list = row.type_id.all() ret = [] for item in type_list: ret.append({'type_name': item.name}) return ret
- 建立视图函数(CBV方式)
from .serializer import GoodsSerializers from rest_framework.viewsets import generics
from rest_framework import permissions # 设置访问权限 class GoodListView(generics.ListAPIView):
queryset = Goods.objects.all()
serializer_class = GoodsSerializers
permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.IsAuthenticated]
# 自定义查询字段
lookup_field = 'time' # 按该参数条件查询数据,默认是按主键
def get(self, request, time):
goods = self.get_object()
serializer = self.get_serializer(goods)
return Response(data = serializer.data)
lookup_url_kwarg = 'id' #URL中的参数
- 建立视图函数(FBV方式)
from django.http import JsonResponse from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from .models import Goods from .serializers import GoodsSerializer def good_list(request): if request.method == "GET": goods = Goods.objects.all() ser = GoodsSerializer(goods, many=True) return JsonResponse(ser.data) elif request.method == "POST": data = JSONParser().parse(request) #将请求参数格式化 ser = GoodsSerializer(data=data) if ser.is_valid(): # 验证数据 ser.save() #保存数据 return JsonResponse(ser.data, status=201) return JsonResponse(ser.errors, status=400) elif request.method == "PUT": data = JSONParser().parse(request) ser = GoodsSerializer(Goods.objects.get(id=request.Get.get('id')), data=data) if ser.is_valid(): ser.save() return JsonResponse(ser.data) return JsonResponse(ser.errors, status=400) elif request.method == "DELETE": Goods.objects.get(id=request.Get.get('id')).delete() return HttpResponse(status=204)
- 建立链接
urlpatterns = [ #path('goods/', GoodListView.as_view(), name='glist'),
path('goods/<int:id>', GoodListView.as_view(), name='glist'),
path('api-auth/', include('rest_framework.urls')), ]