Keerikkattu Chellappan
Keerikkattu Chellappan

Reputation: 515

Flask SQL Alchemy reflection could not assemble any primary key

With Flask SQL Alchemy, I am using the Chinook sqlite db.

sqlalchemy.exc.ArgumentError: Mapper mapped class PlayLists->playlists could not assemble any primary key columns for mapped table 'playlists'

My code is like this. "app/init.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

The app/model.py

from app import db


class PlayLists(db.Model):
    __tablename__ = db.Model.metadata.tables['playlists']

What am I doing wrong?

Upvotes: 0

Views: 342

Answers (1)

Fabio
Fabio

Reputation: 509

In your Playlists class you are assigning db.Model.metadata.tables['playlists'] to __tablename__ . However, db.Model.metadata.tables['playlists'] returns an object of class 'sqlalchemy.sql.schema.Table'. You should instead assign it to a string with the name of the table, as in:

app/model.py

from app import db


class PlayLists(db.Model):
    __tablename__ = 'playlists'

This example works for me, returning the column names of the reflected database:

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

Upvotes: 2

Related Questions