django 連接mysql 數據庫


1、新建一個mysite項目:django-admin startproject mysite 

2、進入項目目錄,新建一個app : python manage.py startapp polls

3、安裝mysqlclient :pip install mysqlclient

4、在settings.py  database中設置數據庫連接配置

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_web',
'USER': 'root',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

5、執行命令: python manage.py migrate

在數據庫中自動創建web系統使用到的表

 

6、編輯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)

 

7、修改mysite/settings.py 文件INSTALLED_APPS 添加  'polls.apps.PollsConfig',

INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]


 
        
7、執行命令:python manage.py makemigrations polls

Migrations for 'polls':
  polls/migrations/0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice

8、執行命令:python manage.py sqlmigrate polls 0001

 9 再執行python manage.py migrate 命令,創建數據庫表

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM