Home  >  Q&A  >  body text

python - Can I still use modles.py to operate mysql after using pymysql in django?

My environment is: Python3.6 django1.11.1 mysql
I use pymysql. When I learned it before, I used sqlite3. Now I use pymysql. Can I still create it by defining classes in models.py? Watch? Why do I write like this and then execute

python manage.py makemigrations
python manage.py migrate

The corresponding table is not generated in mysql?

扔个三星炸死你扔个三星炸死你2661 days ago847

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-06-12 09:25:48

    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(...)

    reply
    0
  • 学习ing

    学习ing2017-06-12 09:25:48

    You need to configure your model folder in INSTALLED_APPS of setting. For example, if you have a file called models.py and the upper-level folder is called app, then you need to configure the app into INSTALLED_APPS before it will be created

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:25:48

    Add two lines of code to xxx/xxx/__init__.py:

    import pymysql
    pymysql.install_as_MySQLdb()

    reply
    0
  • Cancelreply