Skip to content

Commit 52ed5c2

Browse files
authored
Merge pull request #169 from profcomff/fix-order_by--like_diff
fixed order_by - like_diff
2 parents c85cdf4 + 525a4b6 commit 52ed5c2

1 file changed

Lines changed: 13 additions & 12 deletions

File tree

rating_api/models/db.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def like_count(self):
197197
def like_count(cls):
198198
"""SQL выражение для подсчета лайков"""
199199
return (
200-
select(func.count(CommentReaction.uuid))
200+
select(func.coalesce(func.count(CommentReaction.uuid), 0))
201201
.where(and_(CommentReaction.comment_uuid == cls.uuid, CommentReaction.reaction == Reaction.LIKE))
202202
.label('like_count')
203203
)
@@ -211,7 +211,7 @@ def dislike_count(self):
211211
def dislike_count(cls):
212212
"""SQL выражение для подсчета дизлайков"""
213213
return (
214-
select(func.count(CommentReaction.uuid))
214+
select(func.coalesce(func.count(CommentReaction.uuid), 0))
215215
.where(and_(CommentReaction.comment_uuid == cls.uuid, CommentReaction.reaction == Reaction.DISLIKE))
216216
.label('dislike_count')
217217
)
@@ -228,12 +228,15 @@ def like_dislike_diff(cls):
228228
"""SQL выражение для вычисления разницы лайков/дизлайков"""
229229
return (
230230
select(
231-
func.sum(
232-
case(
233-
(CommentReaction.reaction == Reaction.LIKE, 1),
234-
(CommentReaction.reaction == Reaction.DISLIKE, -1),
235-
else_=0,
236-
)
231+
func.coalesce(
232+
func.sum(
233+
case(
234+
(CommentReaction.reaction == Reaction.LIKE, 1),
235+
(CommentReaction.reaction == Reaction.DISLIKE, -1),
236+
else_=0,
237+
)
238+
),
239+
0,
237240
)
238241
)
239242
.where(CommentReaction.comment_uuid == cls.uuid)
@@ -243,10 +246,8 @@ def like_dislike_diff(cls):
243246
@hybrid_method
244247
def order_by_like_diff(cls, asc_order: bool = False):
245248
"""Метод для сортировки по разнице лайков/дизлайков"""
246-
if asc_order:
247-
return cls.like_dislike_diff.asc()
248-
else:
249-
return cls.like_dislike_diff.desc()
249+
# Primary ordering: like-dislike diff (coalesced to 0)
250+
return cls.like_dislike_diff.asc() if asc_order else cls.like_dislike_diff.desc()
250251

251252
@hybrid_method
252253
def has_reaction(self, user_id: int, react: Reaction) -> bool:

0 commit comments

Comments
 (0)