依赖下载
官方推荐的mysql驱动依赖,具体查看参考资料。
pip install mysqlclient==2.0.3
配置
修改settings.py中数据库的配置,默认是内置数据库sqlite3,将其修改为
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name',
'USER': 'root',
'PASSWORD': '******',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
Django Admin
使用Django Admin功能,需要自动创建Admin相关的表,以及创建超级管理员。
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
结果展示
以下页面集成了simpleui,具体请查看 Django Admin | 集成Simple-UI。
参考资料
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.