1.在app下,新建一个文件serializers.py添加数据
# coding=utf-8 from rest_framework import serializers from goods.models import Goods, GoodsCategory class CategorySerializer(serializers.ModelSerializer): class Meta: model = GoodsCategory fields = '__all__' class GoodsSerializer(serializers.ModelSerializer): category = CategorySerializer() #实例化存在外键关系的category class Meta: model = Goods fields = '__all__' 2.在views.py文件里面添加:
from .serializers import GoodsSerializer
from rest_framework import generics
from .models import Goods class GoodsListView(generics.ListAPIView): queryset = Goods.objects.all()[:10] serializer_class = GoodsSerializer 3.在urls.py文件里面添加
from goods.views import GoodsListView
url(r'^goods/$', GoodsListView.as_view(), name='goods-list'),