Opened 5 years ago

Last modified 6 weeks ago

#26001 assigned Cleanup/optimization

Make ModelAdmin.search_fields do an integer lookup for IntegerFields

Reported by: Tim Graham Owned by: Nick Sandford
Component: contrib.admin Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

Currently, all queries are done as string lookups which gives something like this on PostgreSQL, for example: ("admin_views_pluggablesearchperson"."age"::text) = UPPER(20)). It would be more efficient if the admin cast the search value to an integer and used that for the query.

Change History (8)

comment:2 Changed 4 years ago by Akshesh Doshi

Has patch: set

comment:3 Changed 4 years ago by Simon Charette

I think we should favor the approach suggested in #26184 instead.

comment:4 Changed 4 years ago by Tim Graham

Patch needs improvement: set

I agree, let's revisit this if it doesn't.

comment:5 Changed 2 years ago by Tim Graham

Has patch: unset
Patch needs improvement: unset

As far as I tested, you can now use something like search_fields = ['votes__exact'] to do the appropriate query, however, if a non-integer search term is entered, the page crashes with ValueError invalid literal for int() with base 10: 'abc' from IntegerField.get_prep_value(). Probably that exception should be caught in ModelAdmin.get_search_results() and no results returned.

comment:6 Changed 2 years ago by Nick Sandford

Owner: changed from nobody to Nick Sandford
Status: newassigned

comment:7 Changed 2 years ago by Nick Sandford

Has patch: set

comment:8 Changed 2 years ago by Tim Graham

Patch needs improvement: set

comment:9 in reply to:  5 Changed 6 weeks ago by Niclas Olofsson

Replying to Tim Graham:

As far as I tested, you can now use something like search_fields = ['votes__exact'] to do the appropriate query, however, if a non-integer search term is entered, the page crashes with ValueError invalid literal for int() with base 10: 'abc' from IntegerField.get_prep_value(). Probably that exception should be caught in ModelAdmin.get_search_results() and no results returned.

We have to consider that there might be multiple search fields of mixed types though, i.e. search_fields = ['votes__exact', 'title', 'text__contains'], just so the matches for other fields does not get discarded just because one of the fields threw an error.

Instead of trying to catch these errors from .filter() as in the previous patch, we could run to_python() for each search field in order to test if that particular field would raise an exception later on when the query is run.

Last edited 6 weeks ago by Niclas Olofsson (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top