博客
关于我
基于Django框架实现前后端分离(二)
阅读量:671 次
发布时间:2019-03-16

本文共 6915 字,大约阅读时间需要 23 分钟。

基于 Django 实现后端 API 开发

模型建立

在 Django 项目中,模型对应于数据库表结构。本应用将使用四个表:

  • 员工信息表(t_staff_info)
  • 员工证书表(t_staff_cert)
  • 文件表(t_edoc)
  • 数据字典表(t_dict_all)

其中文件表和数据字典表为项目公用表,后续将详细介绍。

from django.db import modelsfrom django.utils import timezoneclass TStaffCert(models.Model):    staff = models.ForeignKey('TStaffInfo', on_delete=models.DO_NOTHING,                             blank=True, null=True, db_column='staff_id')    certType = models.IntegerField(db_column='cert_type', blank=True, null=True)    certId = models.IntegerField(db_column='cert_id', blank=True, null=True)    certName = models.CharField(db_column='cert_name', max_length=128, blank=True, null=True)    certGrade = models.IntegerField(db_column='cert_grade', blank=True, null=True)    certMajor = models.IntegerField(db_column='cert_major', blank=True, null=True)    certFulltime = models.IntegerField(db_column='cert_fulltime', blank=True, null=True)    certCode = models.CharField(db_column='cert_code', max_length=128, blank=True, null=True)    certState = models.IntegerField(db_column='cert_state', blank=True, null=True)    certPerson = models.CharField(db_column='cert_person', max_length=50, blank=True, null=True)    certOrg = models.CharField(db_column='cert_org', max_length=50, blank=True, null=True)    certIssuer = models.CharField(db_column='cert_issuer', max_length=50, blank=True, null=True)    certDate = models.DateField(db_column='cert_date', blank=True, null=True)    validDate = models.DateField(db_column='valid_date', blank=True, null=True)    createDate = models.DateTimeField(db_column='create_date', blank=True, null=True,                                       default=timezone.now())    modifyDate = models.DateTimeField(db_column='modify_date', blank=True, null=True,                                     default=timezone.now())    sts = models.IntegerField()    class Meta:        managed = False        db_table = 't_staff_cert'class TStaffInfo(models.Model):    staffCode = models.CharField(db_column='staff_code', help_text='工号', max_length=32,                               blank=True, null=True)    staffName = models.CharField(db_column='staff_name', help_text='姓名', max_length=128,                               blank=True, null=True)    nation = models.CharField(db_column='nation', max_length=64, blank=True, null=True)    bizGroup = models.CharField(db_column='biz_group', max_length=64, blank=True, null=True)    bizDept = models.CharField(db_column='biz_dept', max_length=64, blank=True, null=True)    dept = models.CharField(db_column='dept', max_length=64, blank=True, null=True)    enrollDate = models.DateField(db_column='enroll_date', blank=True, null=True)    graduateDate = models.DateField(db_column='graduate_date', blank=True, null=True)    workingDate = models.DateField(db_column='working_date', blank=True, null=True)    birthday = models.DateField(db_column='birthday', blank=True, null=True)    idCardCode = models.CharField(db_column='id_card_code', max_length=32, blank=True,                               null=True)    gender = models.IntegerField(db_column='gender', blank=True, null=True)    email = models.CharField(db_column='email', max_length=64, blank=True, null=True)    college = models.CharField(db_column='college', max_length=64, blank=True, null=True)    major = models.CharField(db_column='major', max_length=64, blank=True, null=True)    diploma = models.CharField(db_column='diploma', max_length=64, blank=True, null=True)    diplomaCode = models.CharField(db_column='diploma_code', max_length=64, blank=True,                             null=True)    degree = models.CharField(db_column='degree', max_length=64, blank=True, null=True)    degreeCode = models.CharField(db_column='degree_code', max_length=64, blank=True,                             null=True)    majorType = models.CharField(db_column='major_type', max_length=64, blank=True,                             null=True)    contractUntil = models.DateField(db_column='contract_until', blank=True, null=True)    idCardUntil = models.DateField(db_column='id_card_until', blank=True, null=True)    certFulltime = models.IntegerField(db_column='cert_fulltime', blank=True, null=True)    employer = models.CharField(db_column='employer', max_length=64, blank=True, null=True)    mobilePhone = models.CharField(db_column='mobile_phone', max_length=64, blank=True,                              null=True)    jobState = models.IntegerField(db_column='job_state', blank=True, null=True)    insuranceCode = models.CharField(db_column='insurance_code', max_length=64,                                 blank=True, null=True)    insuranceFrom = models.DateField(db_column='insurance_from', blank=True, null=True)    insuranceTo = models.DateField(db_column='insurance_to', blank=True, null=True)    sts = models.IntegerField(db_column='sts', blank=True, null=True)    comment = models.CharField(db_column='comment', max_length=1024, blank=True, null=True)    createDate = models.DateTimeField(db_column='create_date', blank=True, null=True)    modifyDate = models.DateTimeField(db_column='modify_date', blank=True, null=True,                                    default=timezone.now())    class Meta:        managed = False        db_table = 't_staff_info'

数据库配置

Django默认使用 SQLite,但如果需要其他数据库(如 MySQL),需要修改 settings.py 文件中的数据库配置。

# 在 settings.py 中DATABASES = {    'default': {        'ENGINE': 'django.db.backends=mysql',        'NAME': 'edoc_dev',        'USER': 'edoc',        'PASSWORD': 'edoc123',        'HOST': 'xx.xx.xxx.xx',        'PORT': '3306',    }}

路由配置

路由配置可以使用分路由的方式,美化代码结构,避免主路由文件过长。

from django.contrib import adminfrom django.urls import include, pathurlpatterns = [    # 人员信息管理    path('cms/user/', include('staff.urls')),] + admin.site.urls

视图设计

视图应定义在 views.py 中,使用 Django 和 DRF 的功能。

from django.http import JsonResponsefrom rest_framework.decorators import actionfrom rest_framework import viewsetsfrom rest_framework.permissions import IsAuthenticatedfrom staff.models import TStaffInfofrom staff.serializers import StaffSerializerclass StaffViewSet(viewsets.ModelViewSet):    queryset = TStaffInfo.objects.filter(sts=1)    serializer_class = StaffSerializer    def get_permissions(self):        return [IsAuthenticated()]    @action(methods=['GET'], detail=False)    def list(self, request, format=None):        serializer =StaffSerializer(request.data)        return JsonResponse(serializer.data)

关键点解释

  • ForeignKey 表示外键关联到 TStaffInfo 模型。
  • default 参数设置默认值。
  • help_text 添加字段注释。

时间操作

批量修改时间格式,将 Year 转换为空间值或日期格式。

import datetimefrom django.db import connectiondef transform_time(input_t, type):    now = datetime.datetime.now()    if type == 'ts':        return f"{now.year}"    elif type == 'te':        return f"{now.year - int(input_t.split('-')[0])}-12-31"    elif type in ['S', 's']:        timestamp = int(input_t)        return now.strftime("%Y-%m-%d %H:%M:%S") if timestamp else None

通过以上配置和实现,可以快速搭建一个员工信息管理系统,支持 CRUD 操作。

转载地址:http://oblqz.baihongyu.com/

你可能感兴趣的文章
Webpack 基本环境搭建
查看>>
mysql5.7 安装版 表不能输入汉字解决方案
查看>>
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7.19安装图解_mysql5.7.19 winx64解压缩版安装配置教程
查看>>
MySQL5.7.37windows解压版的安装使用
查看>>
mysql5.7免费下载地址
查看>>
mysql5.7命令总结
查看>>
mysql5.7安装
查看>>
mysql5.7性能调优my.ini
查看>>
MySQL5.7新增Performance Schema表
查看>>
Mysql5.7深入学习 1.MySQL 5.7 中的新增功能
查看>>
Webpack 之 basic chunk graph
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
Mysql8 数据库安装及主从配置 | Spring Cloud 2
查看>>
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>