8

I created declarative table.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String
from sqlalchemy.dialects.postgresql import UUID
import uuid

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True)
    name = Column(String)

I need to filter data. In the Flask-SQLAlchemy, I do

name = 'foo'
User.query.filter_by(name=name).first()

But if I use SQLAlchemy without Flask, then I get the error:

type object 'User' has no attribute 'query'

The only way that works for me is to filter the data through the session.

engine = create_engine('DATABASE_URL')
Session = sessionmaker(bind=engine)
session = Session()

name = 'foo'
user = session.query(User).filter_by(name=name).first()

session.close()

2 Answers 2

10

The Model.query... idiom is not a default part of the SQLAlchemy ORM; it's a customisation provided by Flask-SQLAlchemy. It is not available in base SQLAlchemy, and that is why you get the error message.

Sign up to request clarification or add additional context in comments.

1 Comment

(Old) vanilla SQLA has an easy enough method for the same as well, if using scoped_session: docs.sqlalchemy.org/en/13/orm/…
2

Why? ...because query object is not set on Base/model object automatically.

Solution is to add this line to your base:

Base.query = SessionLocal.query_property()

(where SessionLocal is instance of scoped_session)

This will make query available on all of your models and should solve your issue.However, mypy and pylint will still be complaining about this (that's how I found this question).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.