| 1 |
import datetime |
| 2 |
import warnings |
| 3 |
from collections import OrderedDict |
| 4 |
|
| 5 |
import django |
| 6 |
from django.conf import settings |
| 7 |
from django.core.exceptions import FieldDoesNotExist, FieldError |
| 8 |
from django.db import models |
| 9 |
from django.db.models.constants import LOOKUP_SEP |
| 10 |
from django.db.models.expressions import Expression |
| 11 |
from django.db.models.fields.related import ForeignObjectRel, RelatedField |
| 12 |
from django.utils import timezone |
| 13 |
from django.utils.encoding import force_str |
| 14 |
from django.utils.text import capfirst |
| 15 |
from django.utils.translation import gettext as _ |
| 16 |
|
| 17 |
from .exceptions import FieldLookupError |
| 18 |
|
| 19 |
|
| 20 |
def deprecate(msg, level_modifier=0): |
| 21 |
warnings.warn(msg, MigrationNotice, stacklevel=3 + level_modifier) |
| 22 |
|
| 23 |
|
| 24 |
class MigrationNotice(DeprecationWarning): |
| 25 |
url = "https://django-filter.readthedocs.io/en/main/guide/migration.html" |
| 26 |
|
| 27 |
def __init__(self, message): |
| 28 |
super().__init__("%s See: %s" % (message, self.url)) |
| 29 |
|
| 30 |
|
| 31 |
class RenameAttributesBase(type): |
| 32 |
""" |
| 33 |
Handles the deprecation paths when renaming an attribute. |
| 34 |
|
| 35 |
It does the following: |
| 36 |
- Defines accessors that redirect to the renamed attributes. |
| 37 |
- Complain whenever an old attribute is accessed. |
| 38 |
|
| 39 |
This is conceptually based on `django.utils.deprecation.RenameMethodsBase`. |
| 40 |
""" |
| 41 |
|
| 42 |
renamed_attributes = () |
| 43 |
|
| 44 |
def __new__(metacls, name, bases, attrs): |
| 45 |
# remove old attributes before creating class |
| 46 |
old_names = [r[0] for r in metacls.renamed_attributes] |
| 47 |
old_names = [name for name in old_names if name in attrs] |
| 48 |
old_attrs = {name: attrs.pop(name) for name in old_names} |
| 49 |
|
| 50 |
# get a handle to any accessors defined on the class |
| 51 |
cls_getattr = attrs.pop("__getattr__", None) |
| 52 |
cls_setattr = attrs.pop("__setattr__", None) |
| 53 |
|
| 54 |
new_class = super().__new__(metacls, name, bases, attrs) |
| 55 |
|
| 56 |
def __getattr__(self, name): |
| 57 |
name = type(self).get_name(name) |
| 58 |
if cls_getattr is not None: |
| 59 |
return cls_getattr(self, name) |
| 60 |
elif hasattr(super(new_class, self), "__getattr__"): |
| 61 |
return super(new_class, self).__getattr__(name) |
| 62 |
return self.__getattribute__(name) |
| 63 |
|
| 64 |
def __setattr__(self, name, value): |
| 65 |
name = type(self).get_name(name) |
| 66 |
if cls_setattr is not None: |
| 67 |
return cls_setattr(self, name, value) |
| 68 |
return super(new_class, self).__setattr__(name, value) |
| 69 |
|
| 70 |
new_class.__getattr__ = __getattr__ |
| 71 |
new_class.__setattr__ = __setattr__ |
| 72 |
|
| 73 |
# set renamed attributes |
| 74 |
for name, value in old_attrs.items(): |
| 75 |
setattr(new_class, name, value) |
| 76 |
|
| 77 |
return new_class |
| 78 |
|
| 79 |
def get_name(metacls, name): |
| 80 |
""" |
| 81 |
Get the real attribute name. If the attribute has been renamed, |
| 82 |
the new name will be returned and a deprecation warning issued. |
| 83 |
""" |
| 84 |
for renamed_attribute in metacls.renamed_attributes: |
| 85 |
old_name, new_name, deprecation_warning = renamed_attribute |
| 86 |
|
| 87 |
if old_name == name: |
| 88 |
warnings.warn( |
| 89 |
"`%s.%s` attribute should be renamed `%s`." |
| 90 |
% (metacls.__name__, old_name, new_name), |
| 91 |
deprecation_warning, |
| 92 |
3, |
| 93 |
) |
| 94 |
return new_name |
| 95 |
|
| 96 |
return name |
| 97 |
|
| 98 |
def __getattr__(metacls, name): |
| 99 |
return super().__getattribute__(metacls.get_name(name)) |
| 100 |
|
| 101 |
def __setattr__(metacls, name, value): |
| 102 |
return super().__setattr__(metacls.get_name(name), value) |
| 103 |
|
| 104 |
|
| 105 |
def try_dbfield(fn, field_class): |
| 106 |
""" |
| 107 |
Try ``fn`` with the DB ``field_class`` by walking its |
| 108 |
MRO until a result is found. |
| 109 |
|
| 110 |
ex:: |
| 111 |
_try_dbfield(field_dict.get, models.CharField) |
| 112 |
|
| 113 |
""" |
| 114 |
# walk the mro, as field_class could be a derived model field. |
| 115 |
for cls in field_class.mro(): |
| 116 |
# skip if cls is models.Field |
| 117 |
if cls is models.Field: |
| 118 |
continue |
| 119 |
|
| 120 |
data = fn(cls) |
| 121 |
if data: |
| 122 |
return data |
| 123 |
|
| 124 |
|
| 125 |
def get_all_model_fields(model): |
| 126 |
opts = model._meta |
| 127 |
|
| 128 |
return [ |
| 129 |
f.name |
| 130 |
for f in sorted(opts.fields + opts.many_to_many) |
| 131 |
if not isinstance(f, models.AutoField) |
| 132 |
and not (getattr(f.remote_field, "parent_link", False)) |
| 133 |
] |
| 134 |
|
| 135 |
|
| 136 |
def get_model_field(model, field_name): |
| 137 |
""" |
| 138 |
Get a ``model`` field, traversing relationships |
| 139 |
in the ``field_name``. |
| 140 |
|
| 141 |
ex:: |
| 142 |
|
| 143 |
f = get_model_field(Book, 'author__first_name') |
| 144 |
|
| 145 |
""" |
| 146 |
fields = get_field_parts(model, field_name) |
| 147 |
return fields[-1] if fields else None |
| 148 |
|
| 149 |
|
| 150 |
def get_field_parts(model, field_name): |
| 151 |
""" |
| 152 |
Get the field parts that represent the traversable relationships from the |
| 153 |
base ``model`` to the final field, described by ``field_name``. |
| 154 |
|
| 155 |
ex:: |
| 156 |
|
| 157 |
>>> parts = get_field_parts(Book, 'author__first_name') |
| 158 |
>>> [p.verbose_name for p in parts] |
| 159 |
['author', 'first name'] |
| 160 |
|
| 161 |
""" |
| 162 |
parts = field_name.split(LOOKUP_SEP) |
| 163 |
opts = model._meta |
| 164 |
fields = [] |
| 165 |
|
| 166 |
# walk relationships |
| 167 |
for name in parts: |
| 168 |
try: |
| 169 |
field = opts.get_field(name) |
| 170 |
except FieldDoesNotExist: |
| 171 |
return None |
| 172 |
|
| 173 |
fields.append(field) |
| 174 |
try: |
| 175 |
if isinstance(field, RelatedField): |
| 176 |
opts = field.remote_field.model._meta |
| 177 |
elif isinstance(field, ForeignObjectRel): |
| 178 |
opts = field.related_model._meta |
| 179 |
except AttributeError: |
| 180 |
# Lazy relationships are not resolved until registry is populated. |
| 181 |
raise RuntimeError( |
| 182 |
"Unable to resolve relationship `%s` for `%s`. Django is most " |
| 183 |
"likely not initialized, and its apps registry not populated. " |
| 184 |
"Ensure Django has finished setup before loading `FilterSet`s." |
| 185 |
% (field_name, model._meta.label) |
| 186 |
) |
| 187 |
|
| 188 |
return fields |
| 189 |
|
| 190 |
|
| 191 |
def resolve_field(model_field, lookup_expr): |
| 192 |
""" |
| 193 |
Resolves a ``lookup_expr`` into its final output field, given |
| 194 |
the initial ``model_field``. The lookup expression should only contain |
| 195 |
transforms and lookups, not intermediary model field parts. |
| 196 |
|
| 197 |
Note: |
| 198 |
This method is based on django.db.models.sql.query.Query.build_lookup |
| 199 |
|
| 200 |
For more info on the lookup API: |
| 201 |
https://docs.djangoproject.com/en/stable/ref/models/lookups/ |
| 202 |
|
| 203 |
""" |
| 204 |
query = model_field.model._default_manager.all().query |
| 205 |
lhs = Expression(model_field) |
| 206 |
lookups = lookup_expr.split(LOOKUP_SEP) |
| 207 |
|
| 208 |
assert len(lookups) > 0 |
| 209 |
|
| 210 |
try: |
| 211 |
while lookups: |
| 212 |
name = lookups[0] |
| 213 |
args = (lhs, name) |
| 214 |
# If there is just one part left, try first get_lookup() so |
| 215 |
# that if the lhs supports both transform and lookup for the |
| 216 |
# name, then lookup will be picked. |
| 217 |
if len(lookups) == 1: |
| 218 |
final_lookup = lhs.get_lookup(name) |
| 219 |
if not final_lookup: |
| 220 |
# We didn't find a lookup. We are going to interpret |
| 221 |
# the name as transform, and do an Exact lookup against |
| 222 |
# it. |
| 223 |
lhs = query.try_transform(*args) |
| 224 |
final_lookup = lhs.get_lookup("exact") |
| 225 |
return lhs.output_field, final_lookup.lookup_name |
| 226 |
lhs = query.try_transform(*args) |
| 227 |
lookups = lookups[1:] |
| 228 |
except FieldError as e: |
| 229 |
raise FieldLookupError(model_field, lookup_expr) from e |
| 230 |
|
| 231 |
|
| 232 |
def handle_timezone(value, is_dst=None): |
| 233 |
if settings.USE_TZ and timezone.is_naive(value): |
| 234 |
# On pre-5.x versions, the default is to use zoneinfo, but pytz |
| 235 |
# is still available under USE_DEPRECATED_PYTZ, and is_dst is |
| 236 |
# meaningful there. Under those versions we should only use is_dst |
| 237 |
# if USE_DEPRECATED_PYTZ is present and True; otherwise, we will cause |
| 238 |
# deprecation warnings, and we should not. See #1580. |
| 239 |
# |
| 240 |
# This can be removed once 4.2 is no longer supported upstream. |
| 241 |
if django.VERSION < (5, 0) and settings.USE_DEPRECATED_PYTZ: |
| 242 |
return timezone.make_aware(value, timezone.get_current_timezone(), is_dst) |
| 243 |
return timezone.make_aware(value, timezone.get_current_timezone()) |
| 244 |
elif not settings.USE_TZ and timezone.is_aware(value): |
| 245 |
return timezone.make_naive(value, datetime.timezone.utc) |
| 246 |
return value |
| 247 |
|
| 248 |
|
| 249 |
def verbose_field_name(model, field_name): |
| 250 |
""" |
| 251 |
Get the verbose name for a given ``field_name``. The ``field_name`` |
| 252 |
will be traversed across relationships. Returns '[invalid name]' for |
| 253 |
any field name that cannot be traversed. |
| 254 |
|
| 255 |
ex:: |
| 256 |
|
| 257 |
>>> verbose_field_name(Article, 'author__name') |
| 258 |
'author name' |
| 259 |
|
| 260 |
""" |
| 261 |
if field_name is None: |
| 262 |
return "[invalid name]" |
| 263 |
|
| 264 |
parts = get_field_parts(model, field_name) |
| 265 |
if not parts: |
| 266 |
return "[invalid name]" |
| 267 |
|
| 268 |
names = [] |
| 269 |
for part in parts: |
| 270 |
if isinstance(part, ForeignObjectRel): |
| 271 |
if part.related_name: |
| 272 |
names.append(part.related_name.replace("_", " ")) |
| 273 |
else: |
| 274 |
return "[invalid name]" |
| 275 |
else: |
| 276 |
names.append(force_str(part.verbose_name)) |
| 277 |
|
| 278 |
return " ".join(names) |
| 279 |
|
| 280 |
|
| 281 |
def verbose_lookup_expr(lookup_expr): |
| 282 |
""" |
| 283 |
Get a verbose, more humanized expression for a given ``lookup_expr``. |
| 284 |
Each part in the expression is looked up in the ``FILTERS_VERBOSE_LOOKUPS`` |
| 285 |
dictionary. Missing keys will simply default to itself. |
| 286 |
|
| 287 |
ex:: |
| 288 |
|
| 289 |
>>> verbose_lookup_expr('year__lt') |
| 290 |
'year is less than' |
| 291 |
|
| 292 |
# with `FILTERS_VERBOSE_LOOKUPS = {}` |
| 293 |
>>> verbose_lookup_expr('year__lt') |
| 294 |
'year lt' |
| 295 |
|
| 296 |
""" |
| 297 |
from .conf import settings as app_settings |
| 298 |
|
| 299 |
VERBOSE_LOOKUPS = app_settings.VERBOSE_LOOKUPS or {} |
| 300 |
lookups = [ |
| 301 |
force_str(VERBOSE_LOOKUPS.get(lookup, _(lookup))) |
| 302 |
for lookup in lookup_expr.split(LOOKUP_SEP) |
| 303 |
] |
| 304 |
|
| 305 |
return " ".join(lookups) |
| 306 |
|
| 307 |
|
| 308 |
def label_for_filter(model, field_name, lookup_expr, exclude=False): |
| 309 |
""" |
| 310 |
Create a generic label suitable for a filter. |
| 311 |
|
| 312 |
ex:: |
| 313 |
|
| 314 |
>>> label_for_filter(Article, 'author__name', 'in') |
| 315 |
'auther name is in' |
| 316 |
|
| 317 |
""" |
| 318 |
name = verbose_field_name(model, field_name) |
| 319 |
verbose_expression = [_("exclude"), name] if exclude else [name] |
| 320 |
|
| 321 |
# iterable lookups indicate a LookupTypeField, which should not be verbose |
| 322 |
if isinstance(lookup_expr, str): |
| 323 |
verbose_expression += [verbose_lookup_expr(lookup_expr)] |
| 324 |
|
| 325 |
verbose_expression = [force_str(part) for part in verbose_expression if part] |
| 326 |
verbose_expression = capfirst(" ".join(verbose_expression)) |
| 327 |
|
| 328 |
return verbose_expression |
| 329 |
|
| 330 |
|
| 331 |
def translate_validation(error_dict): |
| 332 |
""" |
| 333 |
Translate a Django ErrorDict into its DRF ValidationError. |
| 334 |
""" |
| 335 |
# it's necessary to lazily import the exception, as it can otherwise create |
| 336 |
# an import loop when importing django_filters inside the project settings. |
| 337 |
from rest_framework.exceptions import ErrorDetail, ValidationError |
| 338 |
|
| 339 |
exc = OrderedDict( |
| 340 |
( |
| 341 |
key, |
| 342 |
[ |
| 343 |
ErrorDetail(e.message % (e.params or ()), code=e.code) |
| 344 |
for e in error_list |
| 345 |
], |
| 346 |
) |
| 347 |
for key, error_list in error_dict.as_data().items() |
| 348 |
) |
| 349 |
|
| 350 |
return ValidationError(exc) |