Python——Django框架——Model数据库模型

一、设置

1、Django的setting中配置数据库(MySQL配置)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '数据库名称',
        'USER': '数据库用户名',
        'PASSWORD': '数据库密码',
        'HOST': '主机地址',
        'POST': '端口号',
    }
}

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    '你的应用名称',
]

2、应用所在的__init__.py添加

import pymysql
pymysql.install_as_MySQLdb()

3、修改Django包

3.1报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None

解决方法:C:\Users\adong\AppData\Local\Programs\Python\Python36\Lib\site-packages\Django-2.0.3-py3.6.egg\django\db\backends\mysql\base.py

注释掉:

 

if version < (1, 3, 3):
     raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__) 

 

3.2修改:C:\Users\adong\AppData\Local\Programs\Python\Python36\Lib\site-packages\Django-2.0.3-py3.6.egg\django\db\backends\mysql\operations.py

 

 query = query.encode(errors='replace')

 

二、创建Model模型(models.py)

from django.db import models
class user(models.Model):#创建一个表
    id = models.AutoField(primary_key=True)#自增长id
    user = models.CharField(max_length=20)
    password = models.CharField(max_length=20)
    email = models.EmailField()
    phone = models.IntegerField()
    perorg = models.IntegerField()

三、生成数据库表

python manage.py makemigrations 应用名
python manage.py migrate

四、pycharm连接Mysql

4.1错误:【8001】Could not create connection to database server. Attempted reconnect 3 times. Giving up.

解决方法:将URL改成这个:jdbc:mysql://localhost:3306/【表名】?useSSL=false&serverTimezone=UTC

 

转载于:https://www.cnblogs.com/cxys85/p/10862251.html

你可能感兴趣的:(Python——Django框架——Model数据库模型)