后端准备home接口
后端准备home接口
一 创建home-app
创建app
Yanapi\Yanapi\apps> python ../../manage.py startapp home
注册app
INSTALLED_APPS = [
...
'apps.home',
]
二 准备数据库
utils/model.py
from django.db import models
class BaseModel(models.Model):
orders = models.IntegerField(verbose_name='显示顺序')
created_time = models.DateTimeField(verbose_name="创建时间",auto_now_add=True,blank=True)
updated_time = models.DateTimeField(verbose_name="更新时间",auto_now=True,blank=True)
is_show = models.BooleanField(verbose_name="是否上架",default=False)
is_delete = models.BooleanField(verbose_name="逻辑删除",default=False)
class Meta:
abstract = True
home/model.py
from django.db import models
from utils.model import BaseModel
class Banner(BaseModel):
name = models.CharField(verbose_name='标题', max_length=16)
note = models.CharField(verbose_name='标题', max_length=150)
# 存的时候 取得时候会自己进行很多处理
image = models.ImageField(verbose_name='图片', upload_to='banner')
link = models.CharField(verbose_name='跳转连接', max_length=64)
class Meta:
db_table = 'yanapi_banner'
verbose_name = '轮播图表'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
迁移数据库
project\Yanapi> python manage.py makemigrations
project\Yanapi> python manage.py migrate
三 准备接口
主urls
from django.contrib import admin
from django.urls import path,re_path,include
# from django.conf import settings
from settings import dev
from django.views.static import serve
urlpatterns = [
# path('/',)
path('admin/', admin.site.urls),
# 这个只负责访问
re_path(r'media/(?P<path>.*)',serve, {'document_root':dev.MEDIA_ROOT}),
# 路由分发
path(r'home/',include('apps.home.urls'))
]
home/urls
from django.urls import path
from . import views
urlpatterns = [
path('banners/', views.BannerListAPIView.as_view()),
]
home/serializers.py
from rest_framework.serializers import ModelSerializer
from . import models
class BannerModelSerializer(ModelSerializer):
class Meta:
model = models.Banner
fields = ('image', 'link')
home/views.py
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from . import models, serializers
class BannerListAPIView(ListAPIView):
queryset = models.Banner.objects.filter(is_show=True, is_delete=False).order_by('-orders')
serializer_class = serializers.BannerModelSerializer