Many-to-many relationships

Query string arguments and data sorting with Enum

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

Modified files

storeapi/routers/post.py
--- 
+++ 
@@ -1,4 +1,5 @@
 import logging
+from enum import Enum
 from typing import Annotated

 import sqlalchemy
@@ -12,6 +13,7 @@
     UserPost,
     UserPostIn,
     UserPostWithComments,
+    UserPostWithLikes,
 )
 from storeapi.models.user import User
 from storeapi.security import get_current_user
@@ -52,11 +54,22 @@
     return {**data, "id": last_record_id}


-@router.get("/post", response_model=list[UserPost])
-async def get_all_posts():
+class PostSorting(str, Enum):
+    new = "new"
+    old = "old"
+    most_likes = "most_likes"
+
+
+@router.get("/post", response_model=list[UserPostWithLikes])
+async def get_all_posts(sorting: PostSorting = PostSorting.new):
     logger.info("Getting all posts")

-    query = post_table.select()
+    if sorting == PostSorting.new:
+        query = select_post_and_likes.order_by(post_table.c.id.desc())
+    elif sorting == PostSorting.old:
+        query = select_post_and_likes.order_by(post_table.c.id.asc())
+    elif sorting == PostSorting.most_likes:
+        query = select_post_and_likes.order_by(sqlalchemy.desc("likes"))

     logger.debug(query)
storeapi/tests/routers/test_post.py
--- 
+++ 
@@ -115,7 +115,50 @@
     response = await async_client.get("/post")

     assert response.status_code == 200
-    assert response.json() == [created_post]
+    assert created_post.items() <= response.json()[0].items()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+    "sorting, expected_order",
+    [
+        ("new", [2, 1]),
+        ("old", [1, 2]),
+    ],
+)
+async def test_get_all_posts_sorting(
+    async_client: AsyncClient,
+    logged_in_token: str,
+    sorting: str,
+    expected_order: list[int],
+):
+    await create_post("Test Post 1", async_client, logged_in_token)
+    await create_post("Test Post 2", async_client, logged_in_token)
+    response = await async_client.get("/post", params={"sorting": sorting})
+    assert response.status_code == 200
+
+    data = response.json()
+    post_ids = [post["id"] for post in data]
+    assert post_ids == expected_order
+
+
+@pytest.mark.anyio
+async def test_get_all_posts_sort_likes(
+    async_client: AsyncClient, logged_in_token: str
+):
+    await create_post("Test Post 1", async_client, logged_in_token)
+    await create_post("Test Post 2", async_client, logged_in_token)
+    await like_post(2, async_client, logged_in_token)
+    response = await async_client.get("/post", params={"sorting": "most_likes"})
+    assert response.status_code == 200
+    data = response.json()
+    assert [post["id"] for post in data] == [2, 1]
+
+
+@pytest.mark.anyio
+async def test_get_all_post_wrong_sorting(async_client: AsyncClient):
+    response = await async_client.get("/post", params={"sorting": "wrong"})
+    assert response.status_code == 422


 @pytest.mark.anyio