# 策略模板
# core/cache/strategies.py
from django.core.cache import cache
from django.db.models import Max
from apps.content.models import Article


class CategoryCacheStrategy:

    def get_category_articles(self, category_slug):
        cache_key = f"category_{category_slug}"
        cached_data = cache.get(cache_key)

        if not cached_data:
            queryset = self._build_queryset(category_slug)
            cache.set(cache_key, queryset, timeout=None)
            return queryset
        return cached_data

    def _build_queryset(self, category_slug):
        return Article.objects.filter(category__slug=category_slug).annotate(
            last_comment_time=Max('comments__pub_date')).order_by(
                '-last_comment_time', '-pub_date')
