From a9d831e8d01a714f19e31da9eb8bc9e9f95bfbd4 Mon Sep 17 00:00:00 2001 From: imperosol Date: Wed, 20 Nov 2024 17:25:39 +0100 Subject: [PATCH] optimize `User.is_subscribed` and `User.was_subscribed` --- core/models.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/core/models.py b/core/models.py index e435ebfe..1d56e4df 100644 --- a/core/models.py +++ b/core/models.py @@ -387,14 +387,21 @@ class User(AbstractUser): @cached_property def was_subscribed(self) -> bool: + if "is_subscribed" in self.__dict__ and self.is_subscribed: + # if the user is currently subscribed, he is an old subscriber too + # if the property has already been cached, avoid another request + return True return self.subscriptions.exists() @cached_property def is_subscribed(self) -> bool: - s = self.subscriptions.filter( + if "was_subscribed" in self.__dict__ and not self.was_subscribed: + # if the user never subscribed, he cannot be a subscriber now. + # if the property has already been cached, avoid another request + return False + return self.subscriptions.filter( subscription_start__lte=timezone.now(), subscription_end__gte=timezone.now() - ) - return s.exists() + ).exists() @cached_property def account_balance(self):