Skip to content

FastAPI Sqlalchemy - *** AttributeError: 'generator' object has no attribute 'query' #113

Open
@vncntk

Description

@vncntk

Hi, I'm trying to integrate this with fastapi and sqlalchemy. But I've stumbled upon this error when querying the models. Here's the code structure.

*** AttributeError: 'generator' object has no attribute 'query'

## db.py
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URI = os.getenv("DB_URI")
SessionLocal = sessionmaker(bind=create_engine(DATABASE_URI))

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


## models.py
class BaseModel(Base, AllFeaturesMixin):
    __abstract__ = True
    pass

class User(BaseModel):
    __tablename__ = "users"

   id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        server_default=text("gen_random_uuid()"),
    )

BaseModel.set_session(get_db())


## routes.py
@router.get("/")
def get_users() -> List[UserOutput]: # def get_users(db: Session = Depends(get_db))
      # users = db.query(User).all()
      return User.all() # error here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions