Django创建mysql数据表流程
在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无法建立数据库,需要我们先建立数据库后,再用以上方法建立数据表

浙公网安备 33010602011771号