1. 程式人生 > >django1.x+python2生成mysql遷移檔案出錯,'Did you install mysqlclient or MySQL-python?' % e

django1.x+python2生成mysql遷移檔案出錯,'Did you install mysqlclient or MySQL-python?' % e

在django+python2生成mysql遷移檔案時,出錯以下錯誤:

 File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "D:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute
    django.setup()
  File "D:\Python27\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "D:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "D:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "D:\Python27\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "D:\Python27\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "D:\Python27\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "D:\Python27\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "D:\Python27\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "D:\Python27\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "D:\Python27\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "D:\Python27\lib\site-packages\django\db\utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "D:\Python27\lib\site-packages\django\db\utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "D:\Python27\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "D:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module>
    'Did you install mysqlclient or MySQL-python?' % e
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 20: ordinal not in range(128)

這是因為Python版本問道,MySQLdb只能在python2中用,在python3中,已經淘汰,不能使用了。

解決方法,在django專案中根目錄下的__init__.py檔案中新增兩行程式碼即可。

import pymysql

pymysql.install_as_MySQLdb()