应用目录下新建一个serializer.py 例如:/home/serializer.py
from rest_framework import serializers
from . import models
class BannerModelSerializer(serializers.ModelSerializer):
class Meta:
# 指定轮播图数据模型
model = models.Banner
# 指定需要返回的数据,例如只需要 title, link, img_url字段的数据
fields = ['title', 'link', 'img_url']
class NavModelsSerializer(serializers.ModelSerializer):
class Meta:
# 指定导航数据模型
model = models.Nav
# 指定需要返回的数据
fields = ['id', 'title', 'link', 'is_site']
编写视图层代码:/home/views.py
from rest_framework.generics import ListAPIView
from . import models
from .serializer import BannerModelSerializer, NavModelsSerializer
# banner轮播图
class BannerView(ListAPIView):
queryset = models.Banner.objects.filter(is_show=True, is_delete=False).order_by('orders')[0:contains.BANNER_LENGTH]
serializer_class = BannerModelSerializer
# 顶部导航栏
class NavTopView(ListAPIView):
queryset = models.Nav.objects.filter(is_show=True, is_delete=False, position=1).order_by('orders')[0:contains.NAV_TOP_LENGTH]
serializer_class = NavModelsSerializer
路由层代码:/home/urls.py
from django.urls import path
from . import views
urlpatterns = [
# banner接口
path(r'banner/', views.BannerView.as_view()),
# 导航栏接口
path(r'nav/top/', views.NavTopView.as_view()),
]
至此,就写好了两个接口;访问/banner/和/nav/top/查看返回的数据:
相关文章
暂无评论...