依赖下载

官方推荐的mysql驱动依赖,具体查看参考资料。

  1. pip install mysqlclient==2.0.3

配置

修改settings.py中数据库的配置,默认是内置数据库sqlite3,将其修改为

  1. # Database
  2. # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
  3. DATABASES = {
  4. 'default': {
  5. 'ENGINE': 'django.db.backends.mysql',
  6. 'NAME': 'db_name',
  7. 'USER': 'root',
  8. 'PASSWORD': '******',
  9. 'HOST': '127.0.0.1',
  10. 'PORT': '3306'
  11. }
  12. }

Django Admin

使用Django Admin功能,需要自动创建Admin相关的表,以及创建超级管理员。

  1. python manage.py makemigrations
  2. python manage.py migrate
  3. python manage.py createsuperuser

结果展示

以下页面集成了simpleui,具体请查看 Django Admin | 集成Simple-UI。
image.png
image.png

参考资料

MySQL DB API Drivers

MySQL has a couple drivers that implement the Python Database API described in PEP 249:

  • mysqlclient is a native driver. It’s the recommended choice.
  • MySQL Connector/Python is a pure Python driver from Oracle that does not require the MySQL client library or any Python modules outside the standard library.

These drivers are thread-safe and provide connection pooling.
In addition to a DB API driver, Django needs an adapter to access the database drivers from its ORM. Django provides an adapter for mysqlclient while MySQL Connector/Python includes its own.

mysqlclient

Django requires mysqlclient 1.4.0 or later.