-
First Check
Commit to Help
Example Codemodels.py class Category(SQLModel, table=True):
__tablename__ = 'categories'
categoryId: int = Field(primary_key=True, nullable=False)
categoryName: str
tags: List["Tag"] = Relationship(back_populates="category")
class Tag(SQLModel, table=True):
__tablename__ = 'tags'
tagId: int = Field(primary_key=True, nullable=False)
tagName: str
tagNameShort: str
categoryId: int = Field(default=None, foreign_key="categories.categoryId")
category: Category = Relationship(back_populates="tags") api.py @router.get("/tags")
async def get_category_with_tags(session: AsyncSession = Depends(get_session)):
r = await session.execute(select(Category).options(selectinload(Category.tags)).order_by(Category.categoryId))
return r.scalars().all() Descriptionthe r.scalars().all() goes well with an instance of class Category which contains a list of tags belonging to it, but after [
{
"categoryId": 1,
"categoryName": "test"
}
] with no tags included Operating SystemWindows Operating System DetailsNo response SQLModel Version0.0.8 Python Version3.11.1 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
JackySu
Feb 21, 2023
Replies: 1 comment
-
this issue can be solved by these modifications class CategoryBase(SQLModel):
categoryId: int = Field(primary_key=True, nullable=False)
categoryName: str
class Category(CategoryBase, table=True):
__tablename__ = 'categories'
tags: List["Tag"] = Relationship(back_populates="category")
class CategoryWithTags(CategoryBase):
tags: List["Tag"] = []
CategoryWithTags.update_forward_refs() api.py @router.get("/tags", response_model=List[CategoryWithTags])
async def get_category_with_tags(session: AsyncSession = Depends(get_session)) -> List[CategoryWithTags]:
r = await session.execute(select(Category).options(selectinload(Category.tags)).order_by(Category.categoryId))
return r.scalars().all() references to the document https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/ |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JackySu
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this issue can be solved by these modifications
models.py
api.py