7 django数据库配置

1 mysql数据库配置

若想将模型转为mysql数据库中的表,需要在settings中配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':'book',  # 要连接的数据库,连接前需要创建好
        'USER':'root',# 连接数据库的用户名
        'PASSWORD':'',# 连接数据库的密码
        'HOST':'127.0.0.1',  # 连接主机,默认本级
        'PORT':3306 #  端口 默认3306
    }
}

注意1:NAME即数据库的名字,在mysql连接前该数据库必须已经创建,而上面的sqlite数据库下的db.sqlite3则是项目自动创建 USER和PASSWORD分别是数据库的用户名和密码。设置完后,再启动我们的Django项目前,我们需要激活我们的mysql。然后,启动项目,会报错:no module named MySQLdb 。这是因为django默认你导入的驱动是MySQLdb,可是MySQLdb 对于py3有很大问题,所以我们需要的驱动是PyMySQL 所以,我们只需要找到项目名文件下的init,在里面写入:

import pymysql
pymysql.install_as_MySQLdb()

最后通过两条数据库迁移命令即可在指定的数据库中创建表 :

python manage.py makemigrations
python manage.py migrate

注意2:确保配置文件中的INSTALLED_APPS中写入我们创建的app名称

INSTALLED_APPS = [
    "book"
]
  • 链接数据库第二个包,可以使用
# 电脑上先提前安装MySQL。
pip install mysqlclient

2 sqlite3数据库配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

3 redis数据库链接

  • Django安装redis包
    pip install django-redis
    
  • settings.py
    CACHES = {
    	"default": {
    		"BACKEND": "django_redis.cache.RedisCache",
    		"LOCATION": "redis://127.0.0.1:6379",
    		"OPTIONS": {
    			"CLIENT_CLASS": "django_redis.client.DefaultClient",
    			"CONNECTION_POOL_KWARGS": {"max_connections": 100}
    			# "PASSWORD": "密码",
    		}
    	}
    }
    

亦或者是:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://:root123@127.0.0.1:6379",  # 安装redis的主机的 IP 和 端口
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {
                "max_connections": 1000,
                "encoding": 'utf-8'
            },
            # "PASSWORD": "root123"  # redis密码
        }
    }
}
  • 手动操作redis
from django_redis import get_redis_connection

conn = get_redis_connection("default")
conn.set("xx","123123")
conn.get("xx")
posted @ 2022-08-03 17:14  角角边  Views(75)  Comments(0)    收藏  举报