19

I'm using SQLAlchemy and Pycharm, but PyCharm can't see methods of SQLAlchemy for autocomplete function.

Code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.sqlite3'
db = SQLAlchemy(app)


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(16), index=True, unique=True)

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

For example, if I want call SQLAlchemy method of User class i must type full method name manually User.query.filter_by(username='peter').first() Autocomplete example

How to make autocomplete work for SQLAlchemy?

1) Yes, project was reloaded several times
2) Yes, right interpreter in File | settings | Project
3) Yes, PyCharm is not in Power Save Mode
4) Yes, I have Professional edition.

Chemoday
  • 191
  • 1
  • 8
  • 1
    Possible duplicate of [PyCharm SQLAlchemy autocomplete](http://stackoverflow.com/questions/21793590/pycharm-sqlalchemy-autocomplete) – M.A.K. Simanto Aug 23 '16 at 12:16

3 Answers3

16

PyCharm (or any other IDE) can't find most methods (query(), add(), commit() etc) as they are not defined in flask_sqlalchemy.SQLAlchemy class. SQLAlchemy methods are added to flask_sqlalchemy.SQLAlchemy objects dynamically during initialization. You can find this initialization function in flask_sqlalchemy module:

def _include_sqlalchemy(obj):
    for module in sqlalchemy, sqlalchemy.orm:
        for key in module.__all__:
            if not hasattr(obj, key):
                setattr(obj, key, getattr(module, key))

Just for the testing: you can type from sqlalchemy.orm import Query. I think PyCharm will find it's objects just fine.

I can't suggest any solution, maybe someone else here know about possibility of dynamically added attributes autocompletion.

Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
14
class User(db.Model):
    query: db.Query # Type hint here
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(16), index=True, unique=True)

adding type hint query: db.Query enter image description here

Tal Leibman
  • 306
  • 4
  • 4
0

just use like this

class Aa(db.Model):
    query: db.Query = db.session.query_property()
    __tablename__ = 'aa'
    name = db.Column(db.String)
    age = db.Column(db.Integer)
    uuid = db.Column(db.Integer, primary_key=True, server_default=db.FetchedValue())

enter image description here

then we got

print(Aa.query.first()) # <Aa 1>
Mike Smith
  • 527
  • 2
  • 6
  • 20