Site/blog/services.py

43 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Optional, List
from django.db.models import F, QuerySet
from django.core.cache import cache
from .models import Article, Category, Comment
def get_published_articles(category_slug: Optional[str] = None) -> QuerySet[Article]:
"""
Возвращает опубликованные статьи с возможностью фильтрации по категории.
Результат кэшируется на 5 минут.
"""
cache_key = f"articles_list_{category_slug or 'all'}"
articles = cache.get(cache_key)
if articles is None:
qs = Article.objects.filter(is_published=True).select_related('category')
if category_slug:
qs = qs.filter(category__slug=category_slug)
articles = list(qs.order_by('-time_create'))
cache.set(cache_key, articles, 300) # 5 минут
return articles
def get_article_by_slug(slug: str) -> Optional[Article]:
"""Получение статьи по slug с учётом публикации."""
try:
return Article.objects.get(slug=slug, is_published=True)
except Article.DoesNotExist:
return None
def increment_article_views(article: Article) -> None:
"""Увеличивает счётчик просмотров статьи."""
Article.objects.filter(pk=article.pk).update(views_count=F('views_count') + 1)
def add_comment_to_article(article: Article, data: dict) -> Comment:
"""Создание комментария к статье (без модерации)."""
comment = Comment.objects.create(
article=article,
author_name=data['author_name'],
author_email=data['author_email'],
content=data['content']
)
# Здесь можно отправить уведомление администратору
return comment