Kuznetsov-M
Kuznetsov-M

Reputation: 435

Why sqlalchemy declarative base object has no attribute 'query'?

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()

Upvotes: 8

Views: 4352

Answers (2)

Tadej
Tadej

Reputation: 426

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).

Upvotes: 2

snakecharmerb
snakecharmerb

Reputation: 55629

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.

Upvotes: 10

Related Questions