﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37562	"Admin changelist search crashes (500) on ""NaN"" and out-of-range datetime terms for `__exact` search_fields"	Kingsley		"Since #36865 (4cecf3039586ea738afafb9a28c946bff42c37c1, new in Django 6.1), `ModelAdmin.get_search_results()` validates each search term for a non-text `<field>__exact` entry in `search_fields` with `formfield().to_python()`, then passes the converted value to the ORM. #37263 fixed this for fields with `choices` and for `BooleanField`. Some values still pass `to_python()` but are rejected later by the model field or by the database backend. The changelist then returns a 500:

 1. `DecimalField`: `forms.DecimalField.to_python()` accepts `NaN`, `Infinity`, `-inf` and `sNaN` (only `forms.DecimalField.validate()` rejects non-finite values). `models.DecimalField.get_prep_value()` then raises `ValidationError` inside `queryset.filter()`. This happens before any SQL runs, so it doesn't depend on the database backend. Each term is OR'd across all `search_fields`, so `q=nan` crashes even when a row's `CharField` contains ""nan"". A multi-word search such as `widget nan` crashes too.
 2. `DateTimeField` with `USE_TZ = True`: a term that overflows when the backend converts it to UTC raises `OverflowError: date value out of range` from `timezone.make_naive()` in `adapt_datetimefield_value()`, when the query is compiled. Examples: `q=0001-01-01` with a current time zone ahead of UTC (e.g. Europe/Paris), and `q=9999-12-31T23:59` with one behind UTC (e.g. America/New_York). I reproduced this on SQLite only. Backends that keep aware datetimes, such as PostgreSQL, may not be affected.
 3. `DateTimeField` with `USE_TZ = False`: a term with a UTC offset, e.g. `q=2020-01-01T00:00+05:00`, raises `ValueError: SQLite backend does not support timezone-aware datetimes when USE_TZ is False.` (SQLite only tested.)

The docs say that for non-text fields with an explicit lookup, ""search terms that are invalid for that field type are skipped"".

To reproduce:

{{{#!python
# models.py
class Item(models.Model):
    title = models.CharField(max_length=40)
    cost = models.DecimalField(max_digits=10, decimal_places=2)

# admin.py
@admin.register(Item)
class ItemAdmin(admin.ModelAdmin):
    search_fields = [""title"", ""cost__exact""]
}}}

Log in as any staff user with the view permission for `Item` and open `/admin/<app>/item/?q=NaN`:

{{{
  File ""django/contrib/admin/options.py"", line 1408, in get_search_results
    queryset = queryset.filter(models.Q.create(term_queries))
  ...
  File ""django/db/models/lookups.py"", line 94, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File ""django/db/models/fields/__init__.py"", line 1924, in get_prep_value
    return self.to_python(value)
  File ""django/db/models/fields/__init__.py"", line 1909, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“NaN” value must be a decimal number.']
}}}

Results (SQLite, all three cases):
 * 5.2.20, 6.0.11: 200
 * b25bc24418 (parent of 4cecf30): 200
 * 4cecf3039586: 500
 * 6.1, 6.1.3, 6.1.4, main (5b0c26e7f6): 500

#37263 fixed the same regression for other field types, but its thread and PR don't mention decimals or datetimes. In the review of [https://github.com/django/django/pull/21754 PR 21754], the stated aim was to ""exclude term values that will crash the query"". #34191 (closed as a duplicate of #26001) was an older crash for terms that can't be parsed as a decimal at all.

I have a patch that also prepares each converted term for the database, with the same calls the `exact` lookup makes (`field.get_db_prep_value(field.get_prep_value(value), connection, prepared=True)`, non-relational fields only). It skips the lookup when that raises `ValidationError`, `ValueError` or `OverflowError`. A narrower alternative that fixes only case 1 is to also call `formfield.validate(value)` for `forms.DecimalField`. `validate()` only checks required-ness and finiteness, not validators such as `max_digits`, so it doesn't reject terms that `clean()` would.

Related, but not fixed by that patch: a `DurationField` `__exact` entry with `q=P999999999D` also gives a 500 on SQLite since 6.1. The error is `OverflowError: Python int too large to convert to SQLite INTEGER`, raised by the sqlite3 driver at execution. Django prepares that value without error, so preparing the term can't detect it. I'm happy to handle it here or in a separate ticket.

This issue was found with the help of an AI assistant (Claude). I reviewed the analysis and re-ran the reproduction myself before filing."	Bug	new	contrib.admin	6.1	Normal		search_fields exact		Unreviewed	0	0	0	0	0	0
