home 模块-轮播图接口实现

home模块

创建home模块

前提:在 luffy 虚拟环境下

1.终端从项目根目录进入apps目录
>: cd luffyapi & cd apps

2.创建app
>: python ../../manage.py startapp home

路由分发

主路由:luffyapi/urls.py
from django.urls import path, re_path, include
urlpatterns = [
	# ...
    path('user/', include('home.urls')),
    # ...
]
子路由:home/urls.py
from django.urls import path, re_path
urlpatterns = [

]

Banner数据表model设计

utils/model.py
from django.db import models

class BaseModel(models.Model):
    orders = models.IntegerField(verbose_name='显示顺序')
    is_show = models.BooleanField(verbose_name="是否上架", default=False)
    is_delete = models.BooleanField(verbose_name="逻辑删除", default=False)

    class Meta:
        abstract = True
home/models.py
from django.db import models
from utils.model import BaseModel

class Banner(BaseModel):
    image = models.ImageField(upload_to='banner', verbose_name='轮播图', null=True, blank=True)
    name = models.CharField(max_length=150, verbose_name='轮播图名称')
    note = models.CharField(max_length=150, verbose_name='备注信息')
    link = models.CharField(max_length=150, verbose_name='轮播图广告地址')

    class Meta:
        db_table = 'luffy_banner'
        verbose_name = '轮播图'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
数据迁移:在大luffyapi路径下的终端
>: python manage.py makemigrations
>: python manage.py migrate

注册home模块:dev.py

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'home',
]

设计Banner数据接口

home/serializers.py
from rest_framework.serializers import ModelSerializer
from . import models
class BannerModelSerializer(ModelSerializer):
    class Meta:
        model = models.Banner
        fields = ('name', 'note', 'image', 'link')
home/views.py
from rest_framework.generics import ListAPIView
from utils.response import APIResponse
from . import models, serializers
class BannerListAPIView(ListAPIView):
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('-orders')
    serializer_class = serializers.BannerModelSerializer
home/urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
    path('banners/', views.BannerListAPIView.as_view())
]
接口
http://api.luffy.cn:8000/home/banner/
posted @ 2019-10-25 22:16  suwanbin_thought  阅读(648)  评论(0编辑  收藏  举报