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. 下一个页面的三角在上面一个页面会出现,在缩放的时候会遮住文字。2. android - mac平台运行快捷键咋按3. mysql优化 - mysql 多表联合查询,求一个效率最高的查询4. weex - Android 原生Vue.js 使用 justify-content: flex-end; 不起作用5. 数据库 - mysql中怎样修改带点的字段名的位置?6. php由5.3升级到5.6后,登录网站,返回的是php代码,不是登录界面,各位大神有知道的吗?7. python - Django ManyToManyField 字段数据在 admin后台 显示不正确,这是怎么回事?8. android - jni生成的char*在NewStringUTF时报错9. javascript - swiper.js嵌套了swiper 初始设置不能向下一个滑动 结束后重新初始10. mysql 能不能创建一个 有列级函数 的联合视图?

网公网安备