通过Flask SQL Alchemy,我正在使用Chinook sqlite数据库。
sqlalchemy.exc.ArgumentError:映射器映射的类PlayLists-> playlists无法为映射表“ playlists”组合任何主键列
我的代码是这样的。 “ app / 初始化 .py”
from flask import Flask
from config import app_config
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.app = app
db.init_app(app)
db.Model.metadata.reflect(db.engine)
Bootstrap(app)
from app import models
return app
app / model.py
from app import db
class PlayLists(db.Model):
__tablename__ = db.Model.metadata.tables['playlists']
我在做什么错了?
答案 0 :(得分:1)
在播放列表类中,您将db.Model.metadata.tables ['playlists']分配给 __ tablename __ 。但是,db.Model.metadata.tables ['playlists']返回类'sqlalchemy.sql.schema.Table'的对象。您应该改为将其分配给具有表名称的字符串,如:
app / model.py
from app import db
class PlayLists(db.Model):
__tablename__ = 'playlists'
此示例对我有用,返回反射数据库的列名:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = 'SUPERSECRET'
app.config['SQLALCHEMY_DATABASE_URI'] = ''mysql+pymysql://user:pass@localhost:port/db''
db = SQLAlchemy(app)
db.init_app(app)
db.Model.metadata.reflect(db.engine)
class User(db.Model):
__tablename__ = "users"
@app.route("/")
def hello():
user = User()
table_columns = str(user.__table__.columns)
return table_columns
if __name__ == "__main__":
app.run()