django 連接mysql 數(shù)據(jù)庫

1、新建一個(gè)mysite項(xiàng)目:django-admin startproject mysite?

2、進(jìn)入項(xiàng)目目錄,新建一個(gè)app :?python manage.py startapp polls

3、安裝mysqlclient :pip install mysqlclient

4、在settings.py ?database中設(shè)置數(shù)據(jù)庫連接配置

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'my_web',

'USER': 'root',

'PASSWORD': 'password',

'HOST': '127.0.0.1',

'PORT': '3306',

}

}

5、執(zhí)行命令:?python manage.py migrate

在數(shù)據(jù)庫中自動(dòng)創(chuàng)建web系統(tǒng)使用到的表


6、編輯polls/models.py文件內(nèi)容

fromdjango.dbimport 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、執(zhí)行命令: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、執(zhí)行命令:python manage.py sqlmigrate polls0001

?9 再執(zhí)行python manage.py migrate 命令,創(chuàng)建數(shù)據(jù)庫表

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容