13.home数据库设计

home数据库设计

轮播图

依赖
安装pillow:
>: pip install pillow

修订manage.py加载dev
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev')
模型类:home/models.py
from django.db import models
class Banner(models.Model):
    """轮播图"""
    # upload_to 存储子目录,真实存放地址会使用配置中的MADIE_ROOT+upload_to
    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='轮播图广告地址')
    orders = models.IntegerField(verbose_name='显示顺序')
    is_show=models.BooleanField(verbose_name="是否上架", default=False)
    is_delete=models.BooleanField(verbose_name="逻辑删除", default=False)

    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/serializers.py
from rest_framework import serializers
from .models import Banner
class BannerModelSerializer(serializers.ModelSerializer):
    """轮播图序列化器"""
    class Meta:
        model = Banner
        # 序列化的目的就是反馈给外界,所以指定的字段就行,其他字段用于orm数据的筛选
        fields = ["image", "link"]
视图模块:home/views.py
from rest_framework.generics import ListAPIView
from .models import Banner
from luffyapi.settings import constant
from .serializers import BannerModelSerializer

class BannerListAPIView(ListAPIView):
    queryset = Banner.objects.filter(is_show=True, is_delete=False).order_by("-orders")[:constant.BANNER_LENGTH]
    serializer_class = BannerModelSerializer
常量配置文件:settings/constant.py
# 轮播图最大长度
BANNER_LENGTH = 7
主路由:urls.py
urlpatterns = [
   	# ...
    path('home/', include("home.urls")),
]
子路由:home/urls.py
urlpatterns = [
   	# ...
    path("banner/", views.BannerListAPIView.as_view()),
]
接口
http://api.luffy.cn:8000/home/banner/

posted @ 2021-01-10 21:54  ABDM  阅读(51)  评论(0编辑  收藏  举报