项目应用代码设计
project\models
设计
之前我们已经写过项目的model,但是写的比较简单,我们这里来丰富一下
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Projects(models.Model):
name = models.CharField(max_length=200, unique=True)
desc = models.CharField(max_length=200, null=True, blank=True, default='')
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
class Meta:
# db_table数据表名称
db_table = 'projects'
# 描述信息,表示单数形式的显示
verbose_name = '项目'
# 表示复数形式的显示
verbose_name_plural = verbose_name
# 根据id 排序
ordering = ['id']
def __str__(self):
return self.name
生成表
生成迁移脚本
(env) D:\code\caseplatform>python manage.py makemigrations
生成数据表
(env) D:\code\caseplatform>python manage.py migrate
project\serializers.py
设计
from rest_framework import serializers
from .models import Projects
class ProjectsSerializer(serializers.ModelSerializer):
class Meta:
model = Projects
exclude = ('update_time',)
extra_kwargs = {
"create_time": {
"read_only": True,
"format": "%Y年%m月%d日 %H:%M:%S"
}
}
project\views
设计
from .models import Projects
from .serializers import ProjectsSerializer
from rest_framework import filters, viewsets
from rest_framework import permissions
class ProjectViewSet(viewsets.ModelViewSet):
# 一般需要指定queryset、serializer_class类属性
queryset = Projects.objects.all()
serializer_class = ProjectsSerializer
# 指定过滤引擎
filter_backends = [filters.SearchFilter, filters.OrderingFilter]
# 过滤的字段
search_fields = ['name', 'desc']
ordering_fields = ['name']
permission_classes = [permissions.IsAuthenticated]
project\urls
设计
注意,这里需要新增urls.py 文件,如果之前已经新增,这里不需要新增
from project import views
from rest_framework import routers
# 创建SimpleRouter路由对象
router = routers.SimpleRouter()
# 注册projects
router.register('projects', views.ProjectViewSet)
urlpatterns = router.urls