Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm SqlAlchemy autocomplete not working

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.

like image 312
Chemoday Avatar asked Aug 23 '16 10:08

Chemoday


People also ask

Why Autocomplete is not working in PyCharm?

If code completion doesn't work, this may be due to one of the following reasons: The Power Save Mode is on (File | Power Save Mode).


2 Answers

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.

like image 196
Sergey Shubin Avatar answered Sep 19 '22 14:09

Sergey Shubin


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

like image 23
Tal Leibman Avatar answered Sep 18 '22 14:09

Tal Leibman