unresolved attribute “Column” in class “SQLAlchemy”

后端 未结 2 785
执念已碎
执念已碎 2021-01-11 17:25

i use pycharm 5.0 and python3.5.And i download all the liarbry by the build-in function of pycharm(setting-project-project interpreter-\"+\").other libraries appear well,but

相关标签:
2条回答
  • 2021-01-11 17:44

    here is what I do.

    from flask_sqlalchemy import SQLAlchemy
    from typing import Callable
    
    
    class MySQLAlchemy(SQLAlchemy):  # Or you can add the below code on the SQLAlchemy directly if you think to modify the package code is acceptable.
        Column: Callable  # Use the typing to tell the IDE what the type is.
        String: Callable
        Integer: Callable
    
    
    db = MySQLAlchemy(app)
    
    
    class User(db.Model, UserMixin):
        __tablename__ = "users"
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(20))  # The message will not show: Unresolved attribute reference 'Column' for class 'SQLAlchemy' 
    
        def __init__(self, *args, **kwargs): 
            super().__init__(*args, **kwargs)
    
    
    def create_test_data():
        db.create_all()
        test_user = User(name='Frank')  # I add __init__, so it will not show you ``Unexpected argument``
        db.session.add(test_user)
        db.session.commit()
    
    0 讨论(0)
  • 2021-01-11 17:49

    The constructor of the flask_sqlalchemy.SQLAlchemy class calls _include_sqlalchemy, which attaches all attributes from sqlalchemy and sqlalchemy.orm to its instances.

    This is only done at runtime and not detected by PyCharm's code inspection.

    It would require flask_sqlalchemy to use a more standard way of importing those attributes, like from sqlalchemy import *. But this would import the attributes into the flask_sqlalchemy module instead of each instance of SQLAlchemy and thus change the way they're accessed.

    I'm not a Python or SQLAlchemy expert and won't judge whether this is good design or not but you could open an issue on https://github.com/mitsuhiko/flask-sqlalchemy and discuss it there.

    0 讨论(0)
提交回复
热议问题