django使用pymysql之后还能使用modles.py来操作mysql吗

我的环境是:Python3.6 + django1.11.1 + mysql
我使用的是pymysql,之前学的时候是用的sqlite3,现在改用pymysql请问在models.py中还是用定义类的方式创建表吗?为什么我这样写然后执行

python manage.py makemigrations
python manage.py migrate

并没有在mysql中生成相应的表呢?

阅读 4.2k
3 个回答
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(...)

需要在setting的INSTALLED_APPS配置你的model文件夹,比如你有一个文件叫models.py上级文件夹叫app,那你需要把app配置到INSTALLED_APPS里面才会创建

在 xxx/xxx/__init__.py 增加两行代码:

import pymysql
pymysql.install_as_MySQLdb()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题