Skip to content

Commit

Permalink
refactor: tidy up recommended query
Browse files Browse the repository at this point in the history
  • Loading branch information
danjac committed Jan 20, 2025
1 parent fc01768 commit 4a8c706
Showing 1 changed file with 17 additions and 24 deletions.
41 changes: 17 additions & 24 deletions radiofeed/podcasts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = user.subscriptions.values("podcast")

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)
)


Expand Down

0 comments on commit 4a8c706

Please sign in to comment.