'Flask-SQLAlchemy- sqlalchemy.exc.ArgumentError: Mapper mapped class could not assemble any primary key columns for mapped table in existing db
I am trying to build an app using Flask and a pre existing sqlite database which has 3 tables. I tried checking what the issue is by trying to import the DB in terminal with a minimal app.
As suggested in this tutorial I used the following code, where city is a table in the db:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////path/test.sqlite'
db = SQLAlchemy(app)
class city(db.Model):
__tablename__ = 'city'
Following this method I was able to import the db and the table in terminal using the following command.
from yourapplication import db
However when I try to do the same with following method as suggested here in the same tutorial, since my project is getting a little bigger and it is the recommended method in the book I am following as well as Flask tutorial, I get the above mentioned error.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'sqlite:////path/test.sqlite'
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
db.init_app(app)
return app
class city(db.Model):
__tablename__ = 'city'
Start of the error message as it might be relevant:
from yourapplication import db
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/yourapplication.py", line 14, in <module>
class city(db.Model):
Now I am not sure the second method is done in the right way in my code since documentation doesn't mention what to do to provide address of the database but I am getting the same error that I have been getting in my original project. My main app also works when all the views and code other than the templates are in the same file.
Since I can import the db in the first method, I assume that problem isn't with the DB and it has primary key. I also know that because the db works perfectly fine in first method and I created the db from a pandas dataframe using the following code:
df1.to_sql("city", conn, dtype={'pkc': 'INTEGER PRIMARY KEY'}, if_exists='replace', index=False)
where pkc has the same value as the index of df1.
This is the book I am following.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
