from typing import Optional, List from sqlmodel import Session from sqlmodel import SQLModel, select from pydantic import RootModel from sqlmodel import Field, Relationship from datetime import datetime class PostBase(SQLModel): content: str timestamp: datetime # model_config = ConfigDict(from_attributes=True) class UserBase(SQLModel): username: str display_name: str # model_config = ConfigDict(from_attributes=True) class Post(PostBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) user_id: int = Field(foreign_key="user.id") user: Optional["User"] = Relationship(back_populates="posts") class User(UserBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) posts: List[Post] = Relationship(back_populates="user") @classmethod def get_all(cls, session: Session) -> List["User"]: statement = select(cls) # .options(selectinload(cls.posts)) users = session.exec(statement).all() return users # Pydantic response models class PostRead(PostBase): id: int user_id: int class PostReadWithUser(PostRead): user: "UserRead" class PostsRead(RootModel[List[PostRead]]): ... class UserRead(UserBase): id: int class UserWithRecentPosts(UserRead): recent_posts: List[PostRead] class UserReadWithPosts(UserRead): posts: List[PostRead] = [] # PostRead.update_forward_refs() # UserRead.update_forward_refs()