Source code for apps.posts.managers

from typing import TYPE_CHECKING

from django.db import models
from django.db.models import Case, Count, F, FloatField, Q, When

from apps.posts.constants import StatusPostChoice

if TYPE_CHECKING:
    from apps.users.models import User


[docs] class NotDeletedQuerySet(models.QuerySet): """ QuerySet that filters out objects which are marked as deleted. """
[docs] def alive(self): return self.filter(is_deleted=False, is_reported=False, author__is_deleted=False)
[docs] def public(self): return self.most_popular().filter( visibility=self.model.VisibilityChoices.PUBLIC, status=StatusPostChoice.PUBLISHED )
[docs] def private_for_user(self, user: "User"): return self.most_popular().filter(visibility=self.model.VisibilityChoices.PRIVATE, author=user)
[docs] def visible_for_user(self, user: "User"): """ Get posts that are visible for the given user: - All public posts - All private posts authored by the given user """ return self.public() | self.private_for_user(user)
[docs] def with_comments_count(self): """ Count comments for post """ return self.annotate( comments_quantity=Count( "comments", filter=Q(comments__is_deleted=False, comments__is_reported=False, comments__author__is_deleted=False), ) )
[docs] class NotDeletedManager(models.Manager): """ Manager that uses the NotDeletedQuerySet to filter out deleted objects. """
[docs] def get_queryset(self) -> NotDeletedQuerySet: return NotDeletedQuerySet(self.model, using=self._db).alive()
[docs] def visible_for_user(self, user): return self.get_queryset().visible_for_user(user)
[docs] def public(self): return self.get_queryset().public()
[docs] class NotDeletedCommentQuerySet(models.QuerySet): """ QuerySet that filters out objects which are marked as deleted. """
[docs] def alive(self): return self.filter(is_deleted=False, author__is_deleted=False)
[docs] class NotDeletedCommentManager(models.Manager): """ Manager that uses the NotDeletedQuerySet to filter out deleted objects. """
[docs] def get_queryset(self) -> NotDeletedQuerySet: return NotDeletedQuerySet(self.model, using=self._db).alive()
[docs] class NotDeletedCommentImageQuerySet(models.QuerySet): """ QuerySet that filters out objects which are marked as deleted. """
[docs] def alive(self): return self.filter(is_deleted=False, comment__is_deleted=False, comment__is_reported=False)
[docs] class NotDeletedCommentImageManager(models.Manager): """ Manager that uses the NotDeletedQuerySet to filter out deleted objects. """
[docs] def get_queryset(self) -> NotDeletedQuerySet: return NotDeletedCommentImageQuerySet(self.model, using=self._db).alive()