diff --git a/Readme.md b/Readme.md index 7907c67..cd97727 100644 --- a/Readme.md +++ b/Readme.md @@ -4,8 +4,6 @@ Simple API for food diary application. ## TODO -- [ ] Sort meals and entries within meals by date -- [ ] Add refresh tokenization - [ ] Add access restriction on each endpoint - [ ] Add tests - [ ] Add default servings diff --git a/fooder/domain/diary.py b/fooder/domain/diary.py index 4d76864..7f8521f 100644 --- a/fooder/domain/diary.py +++ b/fooder/domain/diary.py @@ -1,18 +1,20 @@ from sqlalchemy.orm import relationship, Mapped, mapped_column, joinedload from sqlalchemy import ForeignKey, Integer, Date from sqlalchemy import select +from sqlalchemy.sql.selectable import Select from sqlalchemy.ext.asyncio import AsyncSession from datetime import date from typing import Optional from .base import Base, CommonMixin from .meal import Meal +from .entry import Entry class Diary(Base, CommonMixin): """Diary represents user diary for given day""" - meals: Mapped[list[Meal]] = relationship(lazy="selectin") + meals: Mapped[list[Meal]] = relationship(lazy="selectin", order_by=Meal.order) date: Mapped[date] = mapped_column(Date) user_id: Mapped[int] = mapped_column(Integer, ForeignKey("user.id")) @@ -48,6 +50,18 @@ class Diary(Base, CommonMixin): """ return sum(meal.fat for meal in self.meals) + @classmethod + def query(cls, user_id: int) -> Select: + """get_all.""" + query = ( + select(cls) + .where(cls.user_id == user_id) + .options( + joinedload(cls.meals).joinedload(Meal.entries).joinedload(Entry.product) + ) + ) + return query + @classmethod async def get_diary( cls, session: AsyncSession, user_id: int, date: date diff --git a/fooder/domain/meal.py b/fooder/domain/meal.py index 0bd37c7..e099e46 100644 --- a/fooder/domain/meal.py +++ b/fooder/domain/meal.py @@ -15,7 +15,7 @@ class Meal(Base, CommonMixin): name: Mapped[str] order: Mapped[int] diary_id: Mapped[int] = mapped_column(Integer, ForeignKey("diary.id")) - entries: Mapped[list[Entry]] = relationship(lazy="selectin") + entries: Mapped[list[Entry]] = relationship(lazy="selectin", order_by=Entry.last_changed) @property def calories(self) -> float: