当前位置: 移动技术网 > IT编程>脚本编程>Python > Django创建mysql数据表流程

Django创建mysql数据表流程

2019年08月14日  | 移动技术网IT编程  | 我要评论

曹娥,京东收购1号店,冰山奶爸

在django项目建好后,在setting.py中设置好mysql连接参数:

 1 databases = {
 2     'default': {
 3         'engine': 'django.db.backends.mysql',
 4         'name':'book_2', # 要连接的数据库,连接前需要创建好
 5         'user':'root', # 连接数据库的用户名
 6         'password':'123',# 连接数据库的密码
 7         'host':'127.0.0.1',# 连接主机,默认本级
 8         'port':3306  #  端口 默认3306
 9     }
10 }

在models.py文件中根据自己需求,填写数据表的结构,例如:

 1 class author(models.model):
 2     nid = models.autofield(primary_key=true)
 3     name=models.charfield( max_length=32)
 4     age=models.integerfield()
 5 
 6 class publish(models.model):
 7     nid = models.autofield(primary_key=true)
 8     name=models.charfield( max_length=32)
 9     city=models.charfield( max_length=32)
10     email=models.emailfield()
11 
12 class book(models.model):
13     nid = models.autofield(primary_key=true)
14     title = models.charfield( max_length=32)
15     publishdate=models.datefield()
16     price=models.decimalfield(max_digits=5,decimal_places=2)
17     publish = models.foreignkey(to = 'publish',to_field= 'nid',on_delete=models.cascade)
18     author = models.manytomanyfield(to='author',)

接着在pycharm中的terminal窗口处,输入:

1 python manage.py makemigrations

 

创建过程可能出现的异常:

报错代码1:

1 django.core.exceptions.improperlyconfigured: error loading mysqldb module.
2 did you install mysqlclient?

__init__.py文件夹中添加代码即可解决:

1 import pymysql
2 pymysql.install_as_mysqldb()

报错代码2:

1 django.core.exceptions.improperlyconfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

点击进入报错的地方,把以下代码注释掉即可解决:

1 #if version < (1, 3, 13):
2 #   raise improperlyconfigured('mysqlclient 1.3.13 or newer is #required; you have %s.' % database.__version__)

报错代码3:

1 attributeerror: 'str' object has no attribute 'decode'

点击进入报错的地方,把错误行decode改成encode即可解决:

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

 

解决以上错误后,在terminal中输入:

1 python manage.py migrate

没有报错,到自己的数据库中查看数据表是否创建成功

注:django无法建立数据库,需要我们先建立数据库后,再用以上方法建立数据表

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网