yinzhengjie

             数据库开发-Django ORM的数据库迁移

                                      作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

 

一. Django 项目准备

1>.安装django包

  pip install django=2.2.7

  除了使用pip安装之外,还可以从网上下载Django的压缩包自行安装。在浏览器上输入下载地址:“https://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys”,找到如下图所示对应的Django版本下载到本地后,执行“pip install  你下载的Django软件的本地存放路径"(例如:[pip install  C:\Users\yinzhengjie\softwares\Django‑2.1.4‑py3‑none‑any.whl])

  验证django是否安装成功 

import django        #导入django模块

django.__version__     #查看django的版本 

2>.项目准备

django-admin startproject salary .        #在当前目录下创建一个叫salary的项目

./manage.py startapp employee          #使用上面命令生成的管理脚本"manage.py"来创建应用

3>.打开salary/settings.py主配置文件修改数据库相关的配置

"""
Django settings for salary project.

Generated by \'django-admin startproject\' using Django 2.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = \'dbeqm&74uxuz(@#7)+cau6x$&3&3t6lq9q4iqjo=o92k0jv6^8\'

# SECURITY WARNING: don\'t run with debug turned on in production!
DEBUG = True

LOGGING = {
    \'version\': 1,
    \'disable_existing_loggers\': False,
    \'handlers\': {
        \'console\': {
            \'class\': \'logging.StreamHandler\',
        },
    },
    \'loggers\': {
     \'django.db.backends\': {
            \'handlers\': [\'console\'],
            \'level\': \'DEBUG\',
     },
    },
}


ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    \'django.contrib.admin\',
    \'django.contrib.auth\',
    \'django.contrib.contenttypes\',
    \'django.contrib.sessions\',
    \'django.contrib.messages\',
    \'django.contrib.staticfiles\',
    \'employee\'
]

MIDDLEWARE = [
    \'django.middleware.security.SecurityMiddleware\',
    \'django.contrib.sessions.middleware.SessionMiddleware\',
    \'django.middleware.common.CommonMiddleware\',
    \'django.middleware.csrf.CsrfViewMiddleware\',
    \'django.contrib.auth.middleware.AuthenticationMiddleware\',
    \'django.contrib.messages.middleware.MessageMiddleware\',
    \'django.middleware.clickjacking.XFrameOptionsMiddleware\',
]

ROOT_URLCONF = \'salary.urls\'

TEMPLATES = [
    {
        \'BACKEND\': \'django.template.backends.django.DjangoTemplates\',
        \'DIRS\': [],
        \'APP_DIRS\': True,
        \'OPTIONS\': {
            \'context_processors\': [
                \'django.template.context_processors.debug\',
                \'django.template.context_processors.request\',
                \'django.contrib.auth.context_processors.auth\',
                \'django.contrib.messages.context_processors.messages\',
            ],
        },
    },
]

WSGI_APPLICATION = \'salary.wsgi.application\'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    \'default\': {
        \'ENGINE\': \'django.db.backends.mysql\',
        \'NAME\': \'school\',
        \'USER\': \'jason\',
        \'PASSWORD\': \'yinzhengjie\',
        \'HOST\': \'172.30.1.101\',
        \'PORT\': \'3306\',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        \'NAME\': \'django.contrib.auth.password_validation.UserAttributeSimilarityValidator\',
    },
    {
        \'NAME\': \'django.contrib.auth.password_validation.MinimumLengthValidator\',
    },
    {
        \'NAME\': \'django.contrib.auth.password_validation.CommonPasswordValidator\',
    },
    {
        \'NAME\': \'django.contrib.auth.password_validation.NumericPasswordValidator\',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = \'zh-hans\'

TIME_ZONE = \'Asia/Shanghai\'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = \'/static/\'
salary/settings.py文件内容戳这里 

  注册应用:

  数据库配置:

  时区配置:

  配置Django的日志级别:

4>.Python支持的MySQL驱动

  使用过Django1.11.x的小伙伴应该知道,由于Django默认是使用MySQLDB数据库驱动连接MySQL,不过该驱动不支持python 3.x版本。因此我们可以使用pymysql来代替默认的MySQLDB,编辑根项目路径下的"__init__.py",添加如下图所示的内容即可。

  本篇博客使用的是Django 2.2.x版本,该版本Django默认使用的是mysqlclient(在MySQLdb的基础上,增加了对Python 3的支持)驱动,因此无需做其他配置,只需要安装mysqlclient对应的模块即可。

 

二.数据库迁移

1>.编写Model类

 1 from django.db import models
 2 
 3 # Create your models here.
 4 from django.db import models
 5 class Employee(models.Model):
 6     class Meta:
 7         db_table = \'employees\'
 8 
 9     emp_no = models.IntegerField(primary_key=True)
10     birth_date = models.DateField(null=False)
11     first_name = models.CharField(null=False, max_length=14)
12     last_name = models.CharField(null=False, max_length=16)
13     gender = models.SmallIntegerField(null=False)
14     hire_date = models.DateField(null=False)
15 
16     def __repr__(self):
17         return "<Employee: {} {} {}>".format(
18             self.emp_no,
19             self.first_name,
20             self.last_name
21         )
22 
23     __str__ = __repr__
employee.models.py文件内容

2>.创建表

 python manage.py makemigrations      #将应用中的models.py文件中的更改生成文件并保存到同级目录(migrations)下,默认命名为:"0001_initail.py"

python manage.py migrate      #将上一步migrations目录下生成的"00001_initial.py"文件(里面记录了model.py文件的改动)同步到数据库并生成相应的表。

3>.删除表

python manage.py makemigrations          #将上面的models.py文件代码注释掉后,执行该代码会在migrations目录生成一个文件,如下图所示。

python manage.py migrate        #将修改同步到数据库中,发现数据库中表被删除了,如下图所示。

  

 

分类:

技术点:

相关文章: