48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
from django.db import models
|
|
from django.utils import timezone
|
|
|
|
|
|
class ActiveManager(models.Manager):
|
|
class _QS(models.QuerySet):
|
|
def visible_to(self, user):
|
|
from account.models import UserBlock
|
|
author_field = getattr(self.model, 'AUTHOR_FIELD', 'author')
|
|
|
|
blocked_ids = UserBlock.objects.filter(blocker=user).values_list('blocked_id', flat=True)
|
|
blocking_ids = UserBlock.objects.filter(blocked=user).values_list('blocker_id', flat=True)
|
|
|
|
return (
|
|
self.exclude(**{f'{author_field}__in': blocked_ids})
|
|
.exclude(**{f'{author_field}__in': blocking_ids})
|
|
)
|
|
|
|
def get_queryset(self):
|
|
return self._QS(self.model, using=self._db).filter(is_deleted=False)
|
|
|
|
|
|
class AllManager(models.Manager):
|
|
def get_queryset(self):
|
|
return super().get_queryset()
|
|
|
|
# How to use custom object Managers: add these fields to your model, to override objects behaviour and all_objects behaviour
|
|
# objects = ActiveManager()
|
|
# all_objects = AllManager()
|
|
|
|
|
|
class SoftDeleteModel(models.Model):
|
|
is_deleted = models.BooleanField(default=False)
|
|
deleted_at = models.DateTimeField(null=True, blank=True)
|
|
|
|
objects = ActiveManager()
|
|
all_objects = AllManager()
|
|
|
|
class Meta:
|
|
abstract = True
|
|
|
|
def delete(self, *args, **kwargs):
|
|
self.is_deleted = True
|
|
self.deleted_at = timezone.now()
|
|
self.save()
|
|
|
|
def hard_delete(self, using=None, keep_parents=False):
|
|
super().delete(using=using, keep_parents=keep_parents) |