python - django使用pymysql之后還能使用modles.py來(lái)操作mysql嗎
問(wèn)題描述
我的環(huán)境是:Python3.6 + django1.11.1 + mysql我使用的是pymysql,之前學(xué)的時(shí)候是用的sqlite3,現(xiàn)在改用pymysql請(qǐng)問(wèn)在models.py中還是用定義類的方式創(chuàng)建表嗎?為什么我這樣寫然后執(zhí)行
python manage.py makemigrationspython manage.py migrate
并沒(méi)有在mysql中生成相應(yīng)的表呢?
問(wèn)題解答
回答1:makemigrations, which is responsible for creating new migrations based on the changes you have made to your models.1.先把sqlite3替換成mysql,其他的代碼不變,看能不能生成表.2.如果使用pymysql,一般不用django內(nèi)置model來(lái)寫類對(duì)象.因?yàn)閜ymysql是對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作, 如 cursor.execute(sql, args) 此時(shí)可定義類,創(chuàng)建表可以類里面進(jìn)行(僅僅是例子,不代表唯一) class Bar(object): TABLE = ’bar’ TABLE_SCHEMA = ’’’ create table if not exist `bar`( foo ... ) ’’’ def __init__(self, sql_connection): self.sql_connection = sql_connection self.__create_table() def __create_table(self): cursor = self.sql_connection.cursor() cursor.execute(self.TABLE_SCHEMA) def get(self, foo): cursor = self.sql_connection.cursor() cursor.execute(...)回答2:
需要在setting的INSTALLED_APPS配置你的model文件夾,比如你有一個(gè)文件叫models.py上級(jí)文件夾叫app,那你需要把a(bǔ)pp配置到INSTALLED_APPS里面才會(huì)創(chuàng)建
回答3:在 xxx/xxx/__init__.py 增加兩行代碼:
import pymysqlpymysql.install_as_MySQLdb()
相關(guān)文章:
1. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?2. java - spring boot 如何打包成asp.net core 那種獨(dú)立應(yīng)用?3. java - 在用戶不登錄的情況下,用戶如何添加保存到購(gòu)物車?4. datetime - Python如何獲取當(dāng)前時(shí)間5. javascript - nginx反向代理靜態(tài)資源403錯(cuò)誤?6. docker網(wǎng)絡(luò)端口映射,沒(méi)有方便點(diǎn)的操作方法么?7. 安全性測(cè)試 - nodejs中如何防m(xù)ySQL注入8. javascript - 關(guān)于apply()與call()的問(wèn)題9. docker start -a dockername 老是卡住,什么情況?10. python - 調(diào)用api輸出頁(yè)面,會(huì)有標(biāo)簽出現(xiàn),請(qǐng)問(wèn)如何清掉?
