1创建Banner数据库
由于此数据库中的时间,删除等可以共用,所以我们可以给他单独写一个表模型,最后使它不要在建数据库的时候给建到数据库里面,此段代码可共用,接下来我们继承BaseModels
from django.db import models class BaseModels(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
from utils.models import BaseModels from django.db import models class Banner(BaseModels): 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
此时我们Banner表就建好了
2写Banner接口
通过继承GenericViewSet,ListModelMixin,我们可以很快的将接口写出来,但是如果我们要返回指定格式的数据的话,我们必须从写ListModelMixin中的list方法,把list的数据传给另一个变量,这样我们方便按函数的指定参数传值,由于这个list方法我们也可能多处复用,所以我们又可以给他做一个封装。
from rest_framework.mixins import ListModelMixin from .response import APIResponse class BannerListView(ListModelMixin): def list(self, request, *args, **kwargs): res = super().list(request, *args, **kwargs) return APIResponse(data=res.data)
from luffyapi.utils.listviews import BannerListView from .models import Banner from .serializer import BannerSerializers # Create your views here. from rest_framework.viewsets import GenericViewSet from django.conf import settings class BannerView(GenericViewSet,BannerListView): queryset=Banner.objects.all().filter(is_delete=False,is_show=True).order_by('orders')[:settings.AREA] serializer_class=BannerSerializers
标签:name,models,数据库,接口,luffy,import,True,class,verbose From: https://www.cnblogs.com/shangxin-bai/p/16866935.html