1+ from enum import Enum
12from typing import List , Type
23
34import django_filters
4- from django .db .models import Q
5+ from django .db .models import Q , QuerySet
56from django_filters import CharFilter , BaseInFilter , UUIDFilter
67from django_filters .rest_framework import DjangoFilterBackend
78from rest_framework .exceptions import ValidationError
9+ from safedelete .config import DELETED_ONLY_VISIBLE , DELETED_VISIBLE
10+
11+
12+ class SoftCondition (Enum ):
13+ """
14+ This Enum determines which objects will be filtered regarding their soft deleting state
15+ * it is used in SafeDeleteManager.all
16+ """
17+ NOT_DELETED = None
18+ DELETED_ONLY = DELETED_ONLY_VISIBLE
19+ ALL = DELETED_VISIBLE
820
921
1022class CustomDjangoFilterBackend (DjangoFilterBackend ):
@@ -46,20 +58,26 @@ class BaseFilterSet(django_filters.FilterSet):
4658
4759 1. Opportunity to use special field OR_SEARCH_FIELD that will search
4860 for all char fields and combine results
61+ * Your filter should contain this attribute: 'search = CharFilter(field_name="search", method="OR")'
4962 * This feature works only if your input dictionary has pair [OR_SEARCH_FIELD: some_value]
5063 2. Will raise ValidationError when filter get not valid data
5164 3. Will order result by "-created_at" field
5265 * To use this class your input model type should inherit BaseModel
5366 otherwise you can redefine ORDER_FIELD
5467 * To disable this feature write ORDER_FIELD=None
5568 * Note: symbol '-' is the reverse trigger
69+ 4. SoftCondition by default is NOT_DELETED
5670 """
5771 OR_SEARCH_FIELD = "search"
5872 ORDER_FIELD = "-created_at"
5973
60- def __init__ (self , * args , ** kwargs ):
74+ def __init__ (self , data : dict = None , queryset : QuerySet = None , ** kwargs ):
6175 self .search_value = None
62- super ().__init__ (* args , ** kwargs )
76+ self .force_visibility = SoftCondition .NOT_DELETED
77+ if data is not None :
78+ self .force_visibility = data .get ('DELETED' , SoftCondition .NOT_DELETED )
79+
80+ super ().__init__ (data , queryset , ** kwargs )
6381 if not self .is_valid ():
6482 raise ValidationError (self .errors )
6583
@@ -72,7 +90,8 @@ def OR(self, queryset, field_name, value):
7290
7391 @property
7492 def qs (self ):
75- base_queryset = super ().qs
93+ base_queryset = super ().qs .all (force_visibility = self .force_visibility .value )
94+
7695 if self .ORDER_FIELD :
7796 base_queryset = base_queryset .order_by (self .ORDER_FIELD )
7897
@@ -122,4 +141,5 @@ def filter_by_object_ids(object_name: str):
122141 def func (queryset , name , value ):
123142 values = value .split (',' )
124143 return queryset .filter (** {"{object_name}__in" .format (object_name = object_name ): values })
144+
125145 return func
0 commit comments