python - django使用pymysql之后還能使用modles.py來操作mysql嗎
問題描述
我的環境是:Python3.6 + django1.11.1 + mysql我使用的是pymysql,之前學的時候是用的sqlite3,現在改用pymysql請問在models.py中還是用定義類的方式創建表嗎?為什么我這樣寫然后執行
python manage.py makemigrationspython manage.py migrate
并沒有在mysql中生成相應的表呢?
問題解答
回答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內置model來寫類對象.因為pymysql是對數據庫進行操作, 如 cursor.execute(sql, args) 此時可定義類,創建表可以類里面進行(僅僅是例子,不代表唯一) 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文件夾,比如你有一個文件叫models.py上級文件夾叫app,那你需要把app配置到INSTALLED_APPS里面才會創建
回答3:在 xxx/xxx/__init__.py 增加兩行代碼:
import pymysqlpymysql.install_as_MySQLdb()
相關文章:
1. javascript - 如圖,百度首頁,查看源代碼為什么什么都沒有?2. android - weex 項目createInstanceReferenceError: Vue is not defined3. javascript - 為什么clearInterVal不起作用呢?4. html - 關于CSS實現border的0.5px設置?5. PHPExcel表格導入數據庫怎么導入6. android - 哪位大神知道java后臺的api接口的對象傳到前端后輸入日期報錯,是什么情況?求大神指點7. pdo 寫入到數據庫的內容為中文的時候寫入亂碼8. PHP類封裝的插入數據,總是插入不成功,返回false;9. vue2.0+webpack 如何使用bootstrap?10. mac連接阿里云docker集群,已經卡了2天了,求問?
