|
1 | 1 | from django.contrib.auth import get_user_model |
2 | 2 | from django.contrib.contenttypes.models import ContentType |
| 3 | +from django.core.cache import cache |
3 | 4 |
|
| 5 | +from core.constants import VIEWS_CACHING_TIMEOUT, LIKES_CACHING_TIMEOUT |
4 | 6 | from core.models import Like, View, Link |
5 | 7 |
|
6 | 8 | User = get_user_model() |
@@ -34,9 +36,15 @@ def get_fans(obj): |
34 | 36 |
|
35 | 37 | def get_likes_count(obj): |
36 | 38 | obj_type = ContentType.objects.get_for_model(obj) |
37 | | - return User.objects.filter( |
38 | | - likes__content_type=obj_type, likes__object_id=obj.id |
39 | | - ).count() |
| 39 | + # cache this |
| 40 | + likes_count = cache.get(f"likes_count_{obj_type}_{obj.id}") |
| 41 | + if likes_count is None: |
| 42 | + likes_count = User.objects.filter( |
| 43 | + likes__content_type=obj_type, likes__object_id=obj.id |
| 44 | + ).count() |
| 45 | + # cache for LIKES_CACHING_TIMEOUT seconds |
| 46 | + cache.set(f"views_count_{obj_type}_{obj.id}", likes_count, LIKES_CACHING_TIMEOUT) |
| 47 | + return likes_count |
40 | 48 |
|
41 | 49 |
|
42 | 50 | def set_like(obj, user, is_liked): |
@@ -76,9 +84,16 @@ def get_viewers(obj): |
76 | 84 |
|
77 | 85 | def get_views_count(obj): |
78 | 86 | obj_type = ContentType.objects.get_for_model(obj) |
79 | | - return User.objects.filter( |
80 | | - views__content_type=obj_type, views__object_id=obj.id |
81 | | - ).count() |
| 87 | + # cache this |
| 88 | + views_count = cache.get(f"views_count_{obj_type}_{obj.id}") |
| 89 | + if views_count is None: |
| 90 | + views_count = User.objects.filter( |
| 91 | + views__content_type=obj_type, views__object_id=obj.id |
| 92 | + ).count() |
| 93 | + # cache for VIEWS_CACHING_TIMEOUT seconds |
| 94 | + cache.set(f"views_count_{obj_type}_{obj.id}", views_count, VIEWS_CACHING_TIMEOUT) |
| 95 | + |
| 96 | + return views_count |
82 | 97 |
|
83 | 98 |
|
84 | 99 | def set_viewed(obj, user, is_viewed): |
|
0 commit comments