@@ -188,6 +188,11 @@ class User(BaseModel):
188188 class Config :
189189 orm_mode = True
190190
191+ class UserWithNotesCount (BaseModel ):
192+ id : int
193+ name : str
194+ notes_count : int
195+
191196 @app .get ("/v1/users" , response_model = Page [User ])
192197 def sqla_13_all_users (session : Session = Depends (), paginate : Paginate = Depends ()):
193198 query = (
@@ -200,6 +205,18 @@ def sqla_14_all_users(paginate: Paginate = Depends()):
200205 query = select (user_cls ).options (joinedload ("notes" )).order_by (user_cls .id )
201206 return paginate (query )
202207
208+ @app .get ("/v2/users-with-notes-count" , response_model = Page [UserWithNotesCount ])
209+ def sqla_14_all_users_with_notes_count (paginate : Paginate = Depends ()):
210+ query = (
211+ select (
212+ user_cls .id , user_cls .name , func .count (note_cls .id ).label ("notes_count" )
213+ )
214+ .join (note_cls )
215+ .order_by (user_cls .id )
216+ .group_by (user_cls )
217+ )
218+ return paginate (query , scalars = False )
219+
203220 def query_count (session : Session , query : Select ) -> int :
204221 return session .execute (select (func .count ()).select_from (user_cls )).scalar ()
205222
@@ -236,6 +253,9 @@ async def client(app):
236253 param (0 , 10 , "/v2/custom/users" , marks = mark .sqlalchemy ("1.4" )),
237254 param (10 , 10 , "/v2/custom/users" , marks = mark .sqlalchemy ("1.4" )),
238255 param (40 , 2 , "/v2/custom/users" , marks = mark .sqlalchemy ("1.4" )),
256+ param (0 , 10 , "/v2/users-with-notes-count" , marks = mark .sqlalchemy ("1.4" )),
257+ param (10 , 10 , "/v2/users-with-notes-count" , marks = mark .sqlalchemy ("1.4" )),
258+ param (40 , 2 , "/v2/users-with-notes-count" , marks = mark .sqlalchemy ("1.4" )),
239259 ],
240260)
241261async def test_functional (client , offset , items_number , path ):
0 commit comments