django框架 -3数据库连接

连接mysql数据库

Django supports MySQL 5.5 and higher.

django 数据库引擎支持sqlite3、postgresql、mysql、oracle,默认使用的是sqllite3

  • 编辑 mysite/settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'cdy',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

有可能报错: Error loading MySQLdb module: No module named 'MySQLdb'
解决步骤:
$ sudo pip3 install pymysql
$ sudo vim mysite/init.py //添加如下两行

 import pymysql
 pymysql.install_as_MySQLdb()
  • 执行如下命令
 $ python3 manage.py  migrate
  • 创建models,修改polls/models.py
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
  • Activating models,修改mysite/settings.py
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
  • 使model生效
$ python3 manage.py makemigrations polls
django框架 -3数据库连接_第1张图片
Paste_Image.png
  • 生成建表语句
$ python3 manage.py sqlmigrate polls 0001
django框架 -3数据库连接_第2张图片
Paste_Image.png
  • 建表
$ python3 manage.py migrate
django框架 -3数据库连接_第3张图片
Paste_Image.png
django框架 -3数据库连接_第4张图片
Paste_Image.png
  • 创建超级管理员
$ python3manage.pycreatesuperuser
Paste_Image.png
  • 修改密码
$ pythonmanage.pychangepasswordadmin 
  • 导入导出数据
$ python3 manage.py dumpdata polls > polls.json
$ python3 manage.py loaddata polls.json
  • 清空数据库
$ python3 manage.py flush
  • 进入数据库命令行
$ python3manage.pydbshell

更多命令,可直接python3 manage.py来查看

[caideyang@localhost mysite]$ python3 manage.py 

Type 'manage.py help ' for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

你可能感兴趣的:(django框架 -3数据库连接)