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

fix: sqlmodel #32

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from src.settings import settings

from .food import *
from .history import *
from .report import *
from .review import *
from .tag import *
from .user import *

Expand Down
6 changes: 3 additions & 3 deletions src/models/food.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

class FoodModel(SQLModel, table=True):
if TYPE_CHECKING:
from .history import HistoryModel
from .report import ReportModel
from .review import ReviewModel

id: int = Field(primary_key=True, default=None, index=True)
name: str
Expand All @@ -25,10 +25,10 @@ class FoodModel(SQLModel, table=True):
sugar: Optional[float]
energy: Optional[float]
type: FoodType
image_src: Optional[str]
image_src: Optional[str] = Field(max_length=500)
barcode_number: Optional[str] = Field(index=True, unique=True)
product_db_id: Optional[int] = Field(index=True)
created_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)

reports: List["ReportModel"] = Relationship(back_populates="food")
reviews: List["ReviewModel"] = Relationship(back_populates="food")
histories: List["HistoryModel"] = Relationship(back_populates="food")
16 changes: 9 additions & 7 deletions src/models/review.py → src/models/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
from sqlmodel import Field, Relationship, SQLModel


class ReviewModel(SQLModel, table=True):
class HistoryModel(SQLModel, table=True):
if TYPE_CHECKING:
from .food import FoodModel
from .tag import ReviewTagModel
from .tag import HistoryTagModel
from .user import UserModel

id: int = Field(primary_key=True, default=None, index=True)
Expand All @@ -18,14 +18,16 @@ class ReviewModel(SQLModel, table=True):
energy: Optional[float]
created_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)

content: Optional[str]

food_id: Optional[int] = Field(
default=None, foreign_key="foodmodel.id", nullable=True
)
food: "FoodModel" = Relationship(back_populates="reviews")
food: Optional["FoodModel"] = Relationship(back_populates="histories")

user_id: int = Field(foreign_key="usermodel.id")
user: "UserModel" = Relationship(back_populates="reviews")
user: "UserModel" = Relationship(back_populates="histories")

review_tags: List["ReviewTagModel"] = Relationship(back_populates="review")
post_content: Optional[str]
post_created_at: Optional[datetime] = Field(
default_factory=datetime.utcnow, nullable=False
)
post_tags: List["HistoryTagModel"] = Relationship(back_populates="history")
23 changes: 11 additions & 12 deletions src/models/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,23 @@


class TagModel(SQLModel, table=True):
id: int = Field(primary_key=True, default=None, index=True)
name: str = Field(index=True, unique=True)
color_background: Optional[str]
color_border: Optional[str]
id: str = Field(primary_key=True, index=True, unique=True)
name: str = Field(unique=True)
color: Optional[str]

review_tags: List["ReviewTagModel"] = Relationship(back_populates="tag")
post_tags: List["HistoryTagModel"] = Relationship(back_populates="tag")


class ReviewTagModel(SQLModel, table=True):
class HistoryTagModel(SQLModel, table=True):
if TYPE_CHECKING:
from .review import ReviewModel
from .history import HistoryModel

id: int = Field(primary_key=True, default=None, index=True)

review_id: int = Field(foreign_key="reviewmodel.id")
review: "ReviewModel" = Relationship(back_populates="review_tags")
history_id: int = Field(foreign_key="historymodel.id")
history: "HistoryModel" = Relationship(back_populates="post_tags")

tag_id: int = Field(foreign_key="tagmodel.id")
tag: "TagModel" = Relationship(back_populates="review_tags")
tag_id: str = Field(foreign_key="tagmodel.id")
tag: "TagModel" = Relationship(back_populates="post_tags")

__table_args__ = (UniqueConstraint("review_id", "tag_id"),)
__table_args__ = (UniqueConstraint("history_id", "tag_id"),)
23 changes: 18 additions & 5 deletions src/models/user.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from datetime import datetime
from typing import TYPE_CHECKING, List, Optional

from sqlmodel import Field, Relationship, SQLModel
Expand All @@ -7,17 +8,29 @@

class UserModel(SQLModel, table=True):
if TYPE_CHECKING:
from .history import HistoryModel
from .report import UserReportModel
from .review import ReviewModel

id: int = Field(default=None, primary_key=True)
username: str
id: int = Field(default=None, index=True, primary_key=True)
nickname: str
email: str = Field(unique=True)
password: str
height: Optional[float]
weight: Optional[float]
birth: Optional[str]
birth: Optional[datetime]
gender: Optional[GenderEnum]
signup_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)

user_reports: List["UserReportModel"] = Relationship(back_populates="user")
reviews: List["ReviewModel"] = Relationship(back_populates="user")
histories: List["HistoryModel"] = Relationship(back_populates="user")
devices: List["DeviceModel"] = Relationship(back_populates="user")


class DeviceModel(SQLModel, table=True):
token: str = Field(primary_key=True, index=True)
notification_after_one_hour: bool = Field(default=False)
notification_after_two_hours: bool = Field(default=False)
notification_after_four_hours: bool = Field(default=False)

user_id: int = Field(foreign_key="usermodel.id")
user: "UserModel" = Relationship(back_populates="devices")
4 changes: 2 additions & 2 deletions src/services/food.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from sqlalchemy.exc import IntegrityError
from sqlmodel import Session, select

from src.models import FoodModel, ReportModel, ReviewModel, engine
from src.models import FoodModel, HistoryModel, ReportModel, engine
from src.schemas import (
DistributionFoodContent,
FoodCreateBody,
Expand Down Expand Up @@ -133,7 +133,7 @@ def get_food_detail(food_id: int) -> FoodDetail:


def get_tags_by_food_id(id: int, session: Session) -> list[Tag]:
post = session.exec(select(ReviewModel).where(ReviewModel.food_id == id)).first()
post = session.exec(select(HistoryModel).where(HistoryModel.food_id == id)).first()
tag_list = []
if post is not None:
tags = post.review_tags
Expand Down
19 changes: 10 additions & 9 deletions src/services/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
from sqlalchemy.orm import joinedload
from sqlmodel import Session, select

from src.models import ReviewModel, ReviewTagModel, engine
from src.models import HistoryModel, HistoryTagModel, engine
from src.schemas import CurrentUser, Nutrients, Review, ReviewCreateBody, Tag
from src.utils.time import kst


def create_review(body: ReviewCreateBody, current_user: CurrentUser) -> int:
review = ReviewModel(
review = HistoryModel(
food_id=body.food_id,
carbohydrate=body.nutrients.carbohydrate,
protein=body.nutrients.protein,
Expand All @@ -33,7 +33,7 @@ def create_review(body: ReviewCreateBody, current_user: CurrentUser) -> int:
try:
with Session(engine) as session:
for tag_id in body.tag_ids:
post_tag = ReviewTagModel(review_id=review.id, tag_id=tag_id)
post_tag = HistoryTagModel(review_id=review.id, tag_id=tag_id)
session.add(post_tag)
session.commit()

Expand All @@ -47,10 +47,10 @@ def search_review(*queries) -> list[Review]:
with Session(engine) as session:
posts = (
session.exec(
select(ReviewModel)
select(HistoryModel)
.where(*queries)
.options(
joinedload(ReviewModel.review_tags).joinedload(ReviewTagModel.tag)
joinedload(HistoryModel.review_tags).joinedload(HistoryTagModel.tag)
)
)
.unique()
Expand Down Expand Up @@ -87,13 +87,14 @@ def search_review(*queries) -> list[Review]:


def search_review_by_food_id(food_id: int) -> list[Review]:
return search_review(ReviewModel.food_id == food_id)
return search_review(HistoryModel.food_id == food_id)


def search_review_by_day(datestr: str, current_user: CurrentUser) -> list[Review]:
print(datestr)
date = datetime.strptime(datestr, "%Y%m%d").astimezone(kst)
return search_review(
ReviewModel.user_id == current_user.id,
ReviewModel.created_at >= date - timedelta(hours=9),
ReviewModel.created_at < date + timedelta(days=1) - timedelta(hours=9),
HistoryModel.user_id == current_user.id,
HistoryModel.created_at >= date - timedelta(hours=9),
HistoryModel.created_at < date + timedelta(days=1) - timedelta(hours=9),
)