Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
vncntk opened this issue Jan 31, 2024 · 1 comment

Comments

@vncntk
Copy link

vncntk commented Jan 31, 2024

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
@michaelbukachi
Copy link
Collaborator

Hi,
Please share a reproducible snippet including the versions of the packages you are using.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants