项目应用代码设计

project\models设计

之前我们已经写过项目的model,但是写的比较简单,我们这里来丰富一下

  1. from django.db import models
  2. from django.contrib.auth.models import User
  3. # Create your models here.
  4. class Projects(models.Model):
  5. name = models.CharField(max_length=200, unique=True)
  6. desc = models.CharField(max_length=200, null=True, blank=True, default='')
  7. create_time = models.DateTimeField(auto_now_add=True)
  8. update_time = models.DateTimeField(auto_now=True)
  9. class Meta:
  10. # db_table数据表名称
  11. db_table = 'projects'
  12. # 描述信息,表示单数形式的显示
  13. verbose_name = '项目'
  14. # 表示复数形式的显示
  15. verbose_name_plural = verbose_name
  16. # 根据id 排序
  17. ordering = ['id']
  18. def __str__(self):
  19. return self.name

生成表

生成迁移脚本

(env) D:\code\caseplatform>python manage.py makemigrations

生成数据表

(env) D:\code\caseplatform>python manage.py migrate

project\serializers.py设计

  1. from rest_framework import serializers
  2. from .models import Projects
  3. class ProjectsSerializer(serializers.ModelSerializer):
  4. class Meta:
  5. model = Projects
  6. exclude = ('update_time',)
  7. extra_kwargs = {
  8. "create_time": {
  9. "read_only": True,
  10. "format": "%Y年%m月%d日 %H:%M:%S"
  11. }
  12. }

project\views 设计

  1. from .models import Projects
  2. from .serializers import ProjectsSerializer
  3. from rest_framework import filters, viewsets
  4. from rest_framework import permissions
  5. class ProjectViewSet(viewsets.ModelViewSet):
  6. # 一般需要指定queryset、serializer_class类属性
  7. queryset = Projects.objects.all()
  8. serializer_class = ProjectsSerializer
  9. # 指定过滤引擎
  10. filter_backends = [filters.SearchFilter, filters.OrderingFilter]
  11. # 过滤的字段
  12. search_fields = ['name', 'desc']
  13. ordering_fields = ['name']
  14. permission_classes = [permissions.IsAuthenticated]

project\urls设计

注意,这里需要新增urls.py 文件,如果之前已经新增,这里不需要新增

  1. from project import views
  2. from rest_framework import routers
  3. # 创建SimpleRouter路由对象
  4. router = routers.SimpleRouter()
  5. # 注册projects
  6. router.register('projects', views.ProjectViewSet)
  7. urlpatterns = router.urls