後臺主頁模組設計
阿新 • • 發佈:2020-08-08
一. 建立home模組#
Copy# 前提:在 luffy 虛擬環境下
# 1.終端從專案根目錄進入apps目錄
cd luffyapi & cd apps
# 2.建立app
python ../../manage.py startapp home
二. 路由分發#
1. 主路由:luffyapi/urls.py#
Copyfrom django.urls import path, re_path, include
urlpatterns = [
# ...
path('home/', include('home.urls')),
# ...
]
2. 子路由:home/urls.py#
Copy
from django.urls import path, re_path
urlpatterns = [
]
三. Banner資料表model設計#
1. utils/model.py#
Copyfrom 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_npython
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
2. home/models.py#
Copyfrom 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
3. 資料遷移:在大luffyapi路徑下的終端#
Copypython manage.py makemigrations
python manage.py migrate
三. 註冊home模組:dev.py#
CopyINSTALLED_APPS = [
'rest_framework',
'home',
]
四. 設計Banner資料介面#
1. home/serializers.py#
Copyfrom rest_framework import serializers
from . import models
class BannerSerializer(serializers.ModelSerializer):
class Meta:
model = models.Banner
fields = ['title', 'image', 'link']
2. home/views.py#
Copyfrom 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
3. home/urls.py#
Copyfrom django.urls import path, include
from utils.router import router
from . import views
# 註冊ViewSet的路由
router.register('banners', views.BannerViewSet, 'banner')
urlpatterns = [
path('', include(router.urls)),
]
4. 介面#
Copyhttp://localhost:8000/home/banners/python