| 1 |
import warnings |
| 2 |
from typing import Any, List, Optional, TypeVar, Union, cast |
| 3 |
|
| 4 |
from django.core.exceptions import ImproperlyConfigured |
| 5 |
from django.db.models import Q, QuerySet |
| 6 |
from pydantic import ConfigDict |
| 7 |
from pydantic.fields import FieldInfo |
| 8 |
from typing_extensions import Literal |
| 9 |
|
| 10 |
from .constants import NOT_SET |
| 11 |
from .schema import Schema |
| 12 |
|
| 13 |
|
| 14 |
ExpressionConnector = Literal["AND", "OR", "XOR"] |
| 15 |
|
| 16 |
DEFAULT_IGNORE_NONE: bool = True |
| 17 |
DEFAULT_CLASS_LEVEL_EXPRESSION_CONNECTOR: ExpressionConnector = "AND" |
| 18 |
DEFAULT_FIELD_LEVEL_EXPRESSION_CONNECTOR: ExpressionConnector = "OR" |
| 19 |
|
| 20 |
|
| 21 |
class FilterLookup: |
| 22 |
""" |
| 23 |
Annotation class for specifying database query lookups in FilterSchema fields. |
| 24 |
|
| 25 |
Example usage: |
| 26 |
class MyFilterSchema(FilterSchema): |
| 27 |
name: Annotated[Union[str, None], FilterLookup("name__icontains")] = None |
| 28 |
search: Annotated[Union[str, None], FilterLookup(["name__icontains", "email__icontains"])] = None |
| 29 |
""" |
| 30 |
|
| 31 |
def __init__( |
| 32 |
self, |
| 33 |
q: Union[str, List[str], None], |
| 34 |
*, |
| 35 |
expression_connector: ExpressionConnector = DEFAULT_FIELD_LEVEL_EXPRESSION_CONNECTOR, |
| 36 |
ignore_none: bool = DEFAULT_IGNORE_NONE, |
| 37 |
): |
| 38 |
""" |
| 39 |
Args: |
| 40 |
q: Database lookup expression(s). Can be: |
| 41 |
- A string like "name__icontains" |
| 42 |
- A list of strings like ["name__icontains", "email__icontains"] |
| 43 |
- Use "__" prefix for implicit field name: "__icontains" becomes "fieldname__icontains" |
| 44 |
expression_connector: How to combine multiple field-level expressions ("OR", "AND", "XOR"). Default is "OR". |
| 45 |
ignore_none: Whether to ignore None values for this field specifically. Default is True. |
| 46 |
""" |
| 47 |
self.q = q |
| 48 |
self.expression_connector = expression_connector |
| 49 |
self.ignore_none = ignore_none |
| 50 |
|
| 51 |
|
| 52 |
T = TypeVar("T", bound=QuerySet) |
| 53 |
|
| 54 |
|
| 55 |
class FilterConfigDict(ConfigDict, total=False): |
| 56 |
ignore_none: bool |
| 57 |
expression_connector: ExpressionConnector |
| 58 |
|
| 59 |
|
| 60 |
class FilterSchema(Schema): |
| 61 |
model_config = FilterConfigDict( |
| 62 |
ignore_none=DEFAULT_IGNORE_NONE, |
| 63 |
expression_connector=DEFAULT_CLASS_LEVEL_EXPRESSION_CONNECTOR, |
| 64 |
) |
| 65 |
|
| 66 |
def custom_expression(self) -> Q: |
| 67 |
""" |
| 68 |
Implement this method to return a combination of filters that will be used |
| 69 |
""" |
| 70 |
raise NotImplementedError |
| 71 |
|
| 72 |
def get_filter_expression(self) -> Q: |
| 73 |
""" |
| 74 |
Returns a Q expression based on the current filters |
| 75 |
""" |
| 76 |
try: |
| 77 |
return self.custom_expression() |
| 78 |
except NotImplementedError: |
| 79 |
return self._connect_fields() |
| 80 |
|
| 81 |
def filter(self, queryset: T) -> T: |
| 82 |
return queryset.filter(self.get_filter_expression()) |
| 83 |
|
| 84 |
def _get_filter_lookup( |
| 85 |
self, field_name: str, field_info: FieldInfo |
| 86 |
) -> Optional[FilterLookup]: |
| 87 |
if not hasattr(field_info, "metadata") or not field_info.metadata: |
| 88 |
return None |
| 89 |
|
| 90 |
filter_lookups = [ |
| 91 |
metadata_item |
| 92 |
for metadata_item in field_info.metadata |
| 93 |
if isinstance(metadata_item, FilterLookup) |
| 94 |
] |
| 95 |
|
| 96 |
if len(filter_lookups) == 0: |
| 97 |
return None |
| 98 |
elif len(filter_lookups) == 1: |
| 99 |
return filter_lookups[0] |
| 100 |
else: |
| 101 |
raise ImproperlyConfigured( |
| 102 |
f"Multiple FilterLookup instances found in metadata of {self.__class__.__name__}.{field_name}.\n" |
| 103 |
f"Use at most one FilterLookup instance per field.\n" |
| 104 |
f"If you need multiple lookups, specify them as a list in a single FilterLookup:\n" |
| 105 |
f"{field_name}: Annotated[{field_info.annotation}, FilterLookup(['lookup1', 'lookup2', ...])]" |
| 106 |
) |
| 107 |
|
| 108 |
def _get_field_q_expression( |
| 109 |
self, |
| 110 |
field_name: str, |
| 111 |
field_info: FieldInfo, |
| 112 |
) -> Union[str, List[str], None]: |
| 113 |
filter_lookup = self._get_filter_lookup(field_name, field_info) |
| 114 |
if filter_lookup: |
| 115 |
return filter_lookup.q |
| 116 |
|
| 117 |
|
| 118 |
return cast( |
| 119 |
Union[str, List[str], None], |
| 120 |
self._get_from_deprecated_field_extra(field_name, field_info, "q"), |
| 121 |
) |
| 122 |
|
| 123 |
def _get_field_expression_connector( |
| 124 |
self, |
| 125 |
field_name: str, |
| 126 |
field_info: FieldInfo, |
| 127 |
) -> Union[ExpressionConnector, None]: |
| 128 |
filter_lookup = self._get_filter_lookup(field_name, field_info) |
| 129 |
if filter_lookup: |
| 130 |
return filter_lookup.expression_connector |
| 131 |
|
| 132 |
|
| 133 |
return cast( |
| 134 |
Union[ExpressionConnector, None], |
| 135 |
self._get_from_deprecated_field_extra( |
| 136 |
field_name, field_info, "expression_connector" |
| 137 |
), |
| 138 |
) |
| 139 |
|
| 140 |
def _get_field_ignore_none( |
| 141 |
self, field_name: str, field_info: FieldInfo |
| 142 |
) -> Union[bool, None]: |
| 143 |
filter_lookup = self._get_filter_lookup(field_name, field_info) |
| 144 |
if filter_lookup: |
| 145 |
return filter_lookup.ignore_none |
| 146 |
|
| 147 |
|
| 148 |
return cast( |
| 149 |
Union[bool, None], |
| 150 |
self._get_from_deprecated_field_extra( |
| 151 |
field_name, field_info, "ignore_none" |
| 152 |
), |
| 153 |
) |
| 154 |
|
| 155 |
def _resolve_field_expression( |
| 156 |
self, field_name: str, field_value: Any, field_info: FieldInfo |
| 157 |
) -> Q: |
| 158 |
func = getattr(self, f"filter_{field_name}", None) |
| 159 |
if callable(func): |
| 160 |
return cast(Q, func(field_value)) |
| 161 |
|
| 162 |
q_expression = self._get_field_q_expression(field_name, field_info) |
| 163 |
expression_connector = ( |
| 164 |
self._get_field_expression_connector(field_name, field_info) |
| 165 |
or DEFAULT_FIELD_LEVEL_EXPRESSION_CONNECTOR |
| 166 |
) |
| 167 |
|
| 168 |
if not q_expression: |
| 169 |
return Q(**{field_name: field_value}) |
| 170 |
elif isinstance(q_expression, str): |
| 171 |
if q_expression.startswith("__"): |
| 172 |
q_expression = f"{field_name}{q_expression}" |
| 173 |
return Q(**{q_expression: field_value}) |
| 174 |
elif isinstance(q_expression, list) and all( |
| 175 |
isinstance(item, str) for item in q_expression |
| 176 |
): |
| 177 |
q = Q() |
| 178 |
for q_expression_part in q_expression: |
| 179 |
if q_expression_part.startswith("__"): |
| 180 |
q_expression_part = f"{field_name}{q_expression_part}" |
| 181 |
q = q._combine( |
| 182 |
Q(**{q_expression_part: field_value}), |
| 183 |
expression_connector, |
| 184 |
) |
| 185 |
return q |
| 186 |
else: |
| 187 |
raise ImproperlyConfigured( |
| 188 |
f"Field {field_name} of {self.__class__.__name__} defines an invalid value for 'q'.\n" |
| 189 |
f"Use FilterLookup annotation: {field_name}: Annotated[{field_info.annotation}, FilterLookup('lookup')]\n" |
| 190 |
f"Alternatively, you can implement {self.__class__.__name__}.filter_{field_name} that must return a Q expression for that field" |
| 191 |
) |
| 192 |
|
| 193 |
def _connect_fields(self) -> Q: |
| 194 |
q = Q() |
| 195 |
class_ignore_none = self.model_config.get("ignore_none", DEFAULT_IGNORE_NONE) |
| 196 |
for field_name, field_info in self.__class__.model_fields.items(): |
| 197 |
filter_value = getattr(self, field_name) |
| 198 |
|
| 199 |
|
| 200 |
if class_ignore_none is False: |
| 201 |
ignore_none = False |
| 202 |
else: |
| 203 |
field_ignore_none = self._get_field_ignore_none(field_name, field_info) |
| 204 |
if field_ignore_none is not None: |
| 205 |
ignore_none = field_ignore_none |
| 206 |
else: |
| 207 |
ignore_none = DEFAULT_IGNORE_NONE |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
field_q = self._resolve_field_expression( |
| 212 |
field_name, filter_value, field_info |
| 213 |
) |
| 214 |
if filter_value is None and ignore_none: |
| 215 |
continue |
| 216 |
q = q._combine( |
| 217 |
field_q, |
| 218 |
self.model_config.get( |
| 219 |
"expression_connector", DEFAULT_CLASS_LEVEL_EXPRESSION_CONNECTOR |
| 220 |
), |
| 221 |
) |
| 222 |
|
| 223 |
return q |
| 224 |
|
| 225 |
def _get_from_deprecated_field_extra( |
| 226 |
self, field_name: str, field_info: FieldInfo, attr: str |
| 227 |
) -> Union[Any, None]: |
| 228 |
""" |
| 229 |
Backward-compatible shim which looks up filtering parameters in the Field's **extra kwargs. |
| 230 |
Consider removing this method in favor of FilterLookup annotation class. |
| 231 |
""" |
| 232 |
field_extra = cast(dict, field_info.json_schema_extra) or {} |
| 233 |
value = field_extra.get(attr, NOT_SET) |
| 234 |
|
| 235 |
if value is not NOT_SET: |
| 236 |
warnings.warn( |
| 237 |
f"Using Pydantic Field with extra keyword arguments ('{attr}') " |
| 238 |
f"in field {self.__class__.__name__}.{field_name} is deprecated. Please use ninja.FilterLookup instead:\n" |
| 239 |
f" from typing import Annotated\n" |
| 240 |
f" from ninja import FilterLookup, FilterSchema\n\n" |
| 241 |
f" class {self.__class__.__name__}(FilterSchema):\n" |
| 242 |
f" {field_name}: Annotated[Optional[...], FilterLookup(q='...', ...)] = None", |
| 243 |
DeprecationWarning, |
| 244 |
stacklevel=4, |
| 245 |
) |
| 246 |
return value |
| 247 |
return None |