python - django使用pymysql之后还能使用modles.py来操作mysql吗
本文介绍了python - 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中生成相应的表呢?
解决方案
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(...)
这篇关于python - django使用pymysql之后还能使用modles.py来操作mysql吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文