Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 999
Kuznetsov-M Avatar asked Jun 18 '26 11:06

Kuznetsov-M


2 Answers

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.

like image 101
snakecharmerb Avatar answered Jun 20 '26 00:06

snakecharmerb


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

like image 24
Tadej Avatar answered Jun 20 '26 01:06

Tadej