Skip to content

Commit 6cfbe79

Browse files
committed
add caching to geography queries
1 parent 7d9cab4 commit 6cfbe79

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

api/models/Geography.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
from typing import List, Optional
22

3+
from django.core.cache import cache
34
from django.db import models
45

56
from api.utils.enums import GeoTypes
67

8+
GEOGRAPHY_CACHE_TTL = 60 * 60 * 6 # 6 hours
9+
710

811
class Geography(models.Model):
912
id = models.AutoField(primary_key=True)
1013
name = models.CharField(max_length=75, unique=True)
11-
code = models.CharField(
12-
max_length=100, null=True, blank=True, unique=False, default=""
13-
)
14+
code = models.CharField(max_length=100, null=True, blank=True, unique=False, default="")
1415
type = models.CharField(max_length=20, choices=GeoTypes.choices)
1516
parent_id = models.ForeignKey(
1617
"self", on_delete=models.CASCADE, null=True, blank=True, default=None
@@ -37,9 +38,7 @@ def get_all_descendant_names(self) -> List[str]:
3738
return descendants
3839

3940
@classmethod
40-
def get_geography_names_with_descendants(
41-
cls, geography_names: List[str]
42-
) -> List[str]:
41+
def get_geography_names_with_descendants(cls, geography_names: List[str]) -> List[str]:
4342
"""
4443
Given a list of geography names, return all names including their descendants.
4544
This is a helper method for filtering that expands parent geographies to include children.
@@ -50,6 +49,11 @@ def get_geography_names_with_descendants(
5049
Returns:
5150
List of geography names including all descendants
5251
"""
52+
cache_key = f"geo_descendants:{':'.join(sorted(geography_names))}"
53+
cached: Optional[List[str]] = cache.get(cache_key)
54+
if cached is not None:
55+
return cached
56+
5357
all_names = set()
5458

5559
for name in geography_names:
@@ -60,7 +64,9 @@ def get_geography_names_with_descendants(
6064
# If geography doesn't exist, just add the name as-is
6165
all_names.add(name)
6266

63-
return list(all_names)
67+
result = list(all_names)
68+
cache.set(cache_key, result, timeout=GEOGRAPHY_CACHE_TTL)
69+
return result
6470

6571
class Meta:
6672
db_table = "geography"

0 commit comments

Comments
 (0)