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
CrudRouter Lazy loading support #38
Comments
Hi There. So by default I believe it supports lazy loading. It all depends on how you've set up your database models, your pydantic models, and your ORM. None of the "lazy loading" is handled by crudrouter but rather your ORM |
Hi, thank you for your answer. I will see that and let you know ;). But I think I had tried to do it with pydantic models and the orm but no way to have the lazy loading. I will try again many ways! |
Hi @awtkns, could you please how to setup database models, pydantic models and orm to have "lazy loading", I tried to find a solution but no way to do that! |
HI @davidgfr below is a full example with sqlalchemy lazy loading from typing import List
from pydantic import BaseModel
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from fastapi import Fastapi
from fastapi_crudrouter import SQLAlchemyCRUDRouter
app = FastAPI()
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def session():
session = SessionLocal()
try:
yield session
session.commit()
finally:
session.close()
class ORMModel(BaseModel):
id: int
class Config:
orm_mode = True
class ChildSchema(ORMModel):
parent_id: int
class ParentSchema(ORMModel):
children: List[ChildSchema] = []
class ParentCreate(ORMModel):
pass
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True, index=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True, index=True)
children = relationship(Child, backref='parent', lazy='joined')
Base.metadata.create_all(bind=engine)
parent_router = SQLAlchemyCRUDRouter(schema=ParentSchema, create_schema=ParentCreate, db_model=Parent, db=session)
child_router = SQLAlchemyCRUDRouter(schema=ChildSchema, db_model=Child, db=session)
app.include_router(parent_router)
app.include_router(child_router) When you go to the |
@davidgfr good to close this now? |
Hi @awtkns , I will check this and let you know before closing the issue! Thank you! |
Hello,
I would like to know if there is a way to have "lazy loading" using crudrouter on fastapi?
Is there a solution or a manner to do it?
Thank you in advance.
The text was updated successfully, but these errors were encountered: