diff --git a/donate/models.py b/donate/models.py index 6fd35769ac10786147b0641245dc8960d9abae5c..f403a55f3ae34c6bf2e46309d26538e2acf7ce5b 100644 --- a/donate/models.py +++ b/donate/models.py @@ -428,15 +428,22 @@ class DonateProjectPage(DonateFormMixin, Page, SubpageMixin, MetadataPageMixin): return self.perex def get_donated_amount(self): - key = f"donated_amount_{self.portal_project_id}" - amount = cache.get(key) - if amount is None: - amount = get_donated_amount_from_api(self.portal_project_id) - if amount is not None: - self.donated_amount = amount - self.save() - cache.set(key, amount) - return self.donated_amount + if self.portal_project_id is None: + return 0 + # instance caching for multiple method calls during one request + if not hasattr(self, "_donated_amount"): + # cache portal API calls (defaults to 5 min) + key = f"donated_amount_{self.portal_project_id}" + amount = cache.get(key) + if amount is None: + amount = get_donated_amount_from_api(self.portal_project_id) + if amount is not None: + # save amount into database to be used if next API calls fails + self.donated_amount = amount + self.save() + cache.set(key, amount) + self._donated_amount = self.donated_amount or 0 + return self._donated_amount @property def donated_percentage(self):