python - django使用pymysql之后還能使用modles.py來操作mysql嗎
問題描述
我的環(huán)境是:Python3.6 + django1.11.1 + mysql我使用的是pymysql,之前學(xué)的時候是用的sqlite3,現(xiàn)在改用pymysql請問在models.py中還是用定義類的方式創(chuàng)建表嗎?為什么我這樣寫然后執(zhí)行
python manage.py makemigrationspython manage.py migrate
并沒有在mysql中生成相應(yīng)的表呢?
問題解答
回答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來寫類對象.因為pymysql是對數(shù)據(jù)庫進(jìn)行操作, 如 cursor.execute(sql, args) 此時可定義類,創(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文件夾,比如你有一個文件叫models.py上級文件夾叫app,那你需要把app配置到INSTALLED_APPS里面才會創(chuàng)建
回答3:在 xxx/xxx/__init__.py 增加兩行代碼:
import pymysqlpymysql.install_as_MySQLdb()
相關(guān)文章:
1. MySQL數(shù)據(jù)庫中文亂碼的原因2. dockerfile - 我用docker build的時候出現(xiàn)下邊問題 麻煩幫我看一下3. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。4. angular.js - 關(guān)于$apply()5. mysql - 新浪微博中的關(guān)注功能是如何設(shè)計表結(jié)構(gòu)的?6. angular.js - Ionic 集成crosswalk后生成的apk在android4.4.2上安裝失敗???7. dockerfile - [docker build image失敗- npm install]8. 如何解決Centos下Docker服務(wù)啟動無響應(yīng),且輸入docker命令無響應(yīng)?9. nignx - docker內(nèi)nginx 80端口被占用10. 請問朱老師,如何配置url訪問路由
