23

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 some problems happens to flask-SQLAlchemy.

i import flask-SQLAlchemy successfully.however,pycharm remind me that "unresolved attribute reference 'Column' in class'SQLAlchemy'"."unresolved attribute reference 'relationship' in class 'SQLAlchemy'" and so on.

I have try some ways ,but they didn't work.for example:1.restart 2.remove and redownload 3.refresh the cache.which mention in PyCharm shows unresolved references error for valid code

code:

from flask import Flask, redirect, render_template, session, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField, SubmitField
import os
from wtforms.validators import data_required


basedir = os.path.abspath(os.path.dirname(__file__))


app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] =\
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True


bootstrap = Bootstrap(app)

db = SQLAlchemy(app)


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role', lazy='dynamic')

    def __repr__(self):
        return '<Role %r>' % self.name


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

    def __repr__(self):
        return '<User %r>' % self.username

how can i solve this problem?

Community
  • 1
  • 1
dogewang
  • 648
  • 1
  • 7
  • 15
  • sth confuses me ......I find that the attribute "Column" 's location is in G:\python\Lib\site-packages\sqlalchemy\sql\schema.py,but the class 'SQLAlchemy' is in G:\python\Lib\site-packages\flask_sqlalchemy\__init__.py, and i didn't find any attribute in class 'SQLAlchemy' 's source code . – dogewang Feb 07 '16 at 01:21
  • Does your code run? That's the important thing. I took a look at the source for flask_sqlalchemy, it looks like it uses some magic to be compatible with the base sqlalchemy lib that PyCharm might not correctly detect. – Seán Hayes Feb 07 '16 at 04:59
  • it can runs.But i want to know the way how python handle this ,that is the relationship between extention lib and origin lib,how do they connect – dogewang Feb 08 '16 at 00:38
  • Did you find your answer? – Abbas Jafari Aug 28 '21 at 09:54

4 Answers4

20

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/pallets/flask-sqlalchemy and discuss it there.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Michael
  • 318
  • 2
  • 7
  • 1
    Per [this comment](https://github.com/pallets/flask-sqlalchemy/issues/999#issuecomment-917046523) from the maintainer it doesn't look like they will be added soon. – snakecharmerb Sep 20 '21 at 09:10
9

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()
Carson
  • 6,105
  • 2
  • 37
  • 45
0

I've ran into the same problem just now.

In short if I just hit Run the code runs with exit code 0 even is PyCharm shows Unresolved attribute reference but for anyone who might make the same mistake as I did before simply hitting Run:

This is the code that I was writing and it showed 'Unresolved attribute reference 'Column' for class 'SQLAlchemy'' also for eg. 'Unresolved attribute reference 'Integer' for class 'SQLAlchemy' '.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///new-books-collection.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 
False
db = SQLAlchemy(app)


class Books(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(250), unique=True, nullable=False)
    author = db.Column(db.String(250), unique=True, nullable=False)
    rating = db.Column(db.Float, nullable=False)


db.create_all()

My problem was that I hovered over Column and Integer and clicked Add method Column() to class SQLAlchemy. Also the same with Integer.

From that moment TypeErrors came up for me because it created these empty methods in __init__.py of SQLAlchemy.

To solve this I used pip install flask_sqlalchemy --upgrade and pip install flask_sqlalchemy. And did not Add methods again. It still showed Unresolved attribute reference, but the code ran with exit code 0 and the database was created, with the right data inside.

Hope that helps!

-1

Check the version of flask_sqlalchemy in your pycharm or environment. i had same problem ,the easiest solution

pip install flask_sqlalchemy --upgrade 

100% its gone work.

Get Gyan
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 15 '21 at 03:51