From f383a79b094c9b5ce7b775792d4a4ba8368c0b92 Mon Sep 17 00:00:00 2001 From: Dan Jacob Date: Mon, 20 Jan 2025 15:19:42 +0200 Subject: [PATCH] refactor: tidy up recommended query --- radiofeed/podcasts/models.py | 41 +++++++++++++++--------------------- 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/radiofeed/podcasts/models.py b/radiofeed/podcasts/models.py index 867cdebca..c7cf19ef4 100644 --- a/radiofeed/podcasts/models.py +++ b/radiofeed/podcasts/models.py @@ -143,38 +143,31 @@ def recommended(self, user: User) -> models.QuerySet["Podcast"]: # pick highest matches # we want the sum of the relevance of the recommendations, grouped by recommended + subscribed = set(user.subscriptions.values_list("podcast", flat=True)) + scores = ( - Recommendation.objects.alias( - is_podcast_subscribed=models.Exists( - user.subscriptions.filter( - podcast=models.OuterRef("podcast"), - ) - ), - is_recommended_subscribed=models.Exists( - user.subscriptions.filter( - podcast=models.OuterRef("recommended"), - ) - ), - ) - .filter( - is_podcast_subscribed=True, - is_recommended_subscribed=False, + Recommendation.objects.filter( + podcast__in=subscribed, recommended=models.OuterRef("pk"), ) .values("score") .order_by("-score") ) - return self.annotate( - relevance=Coalesce( - models.Subquery( - scores.values("score")[:1], + return ( + self.annotate( + relevance=Coalesce( + models.Subquery( + scores.values("score")[:1], + ), + 0, + output_field=models.DecimalField(), ), - 0, - output_field=models.DecimalField(), - ), - ).filter( - models.Q(relevance__gt=0) | models.Q(promoted=True), + ) + .filter( + models.Q(relevance__gt=0) | models.Q(promoted=True), + ) + .exclude(pk__in=subscribed) )