11 后台首页相关接口(l轮波图接口)
作者:互联网
1.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='优先级') #这样写,一迁移数据,会生成一个BaseModel表在数据库中 class Meta: abstract = True #如果写了他,表示虚拟表,不在数据库中生成,只做继承用
home/models.py
from django.db import models # Create your models here. from utils.models 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', ]
2.设计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.urls import path, include from utils.router import router from . import views # 注册ViewSet的路由 router.register('banners', views.BannerViewSet, 'banner') urlpatterns = [ path('', include(router.urls)), ]
接口
http://127.0.0.1:8000/home/banner/
可以数据库迁移后,创建超级用户python manage.py createsuperuser,使用http://127.0.0.1:8000/home/admin,录入轮波图数据,然后再使用http://127.0.0.1:8000/home/banner/访问
标签:11,verbose,name,models,py,接口,home,import,轮波图 来源: https://www.cnblogs.com/Haier123/p/15911143.html