This commit is contained in:
Waylon S. Walker 2025-07-03 09:48:05 -05:00
commit 48c6176c47
12 changed files with 1971 additions and 0 deletions

66
models.py Normal file
View file

@ -0,0 +1,66 @@
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()