luffy04-首頁輪播圖介面

xiaoyurainzi發表於2020-12-24

首頁輪播圖介面

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('home/', 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):
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='建立時間')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='最後更新時間')
    is_delete = models.BooleanField(default=False, verbose_name='是否刪除')
    is_show = models.BooleanField(default=True, verbose_name='是否上架')
    orders = models.IntegerField(verbose_name='優先順序')

    class Meta:
        abstract = True

home/models.py

from django.db import models
from utils.model import BaseModel

class Banner(BaseModel):
    title = models.CharField(max_length=16, unique=True, verbose_name='名稱')
    image = models.ImageField(upload_to='banner', verbose_name='圖片')
    link = models.CharField(max_length=64, verbose_name='跳轉連結')
    info = models.TextField(verbose_name='詳情')  # 也可以用詳情表,寬高出處

    class Meta:
        db_table = 'luffy_banner'
        verbose_name_plural = '輪播圖表'

    def __str__(self):
        return self.title

資料遷移:在大luffyapi路徑下的終端

>: python manage.py makemigrations
>: python manage.py migrate

註冊home模組:dev.py

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

設計Banner資料介面

home/serializers.py

from rest_framework import serializers
from . import models
class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Banner
        fields = ['title', 'image', 'link']

home/views.py

from rest_framework.viewsets import ModelViewSet
from rest_framework import mixins
from . import models, serializers

class BannerViewSet(ModelViewSet, mixins.ListModelMixin):
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializers.BannerSerializer

home/urls.py

from django.conf import settings
from django.views.static import serve

from . import views
# 自動生成路徑
from rest_framework.routers import SimpleRouter

router = SimpleRouter()

router.register('banner', views.BannerViewSet)

urlpatterns = [
    path('', include(router.urls)),  # 方式一
]

# urlpatterns+=router.urls  # 方式二

介面

http://localhost:8000/home/banners/

相關文章