#30256: autocomplete_fields cause one or two extra queries for each field wth foreign key or many to many relation --------------------------------------+------------------------------------ Reporter: George Tantiras | Owner: nobody Type: Cleanup/optimization | Status: new Component: contrib.admin | Version: master Severity: Normal | Resolution: Keywords: autocomplete | Triage Stage: Accepted Has patch: 0 | Needs documentation: 0 Needs tests: 0 | Patch needs improvement: 0 Easy pickings: 0 | UI/UX: 0 --------------------------------------+------------------------------------ Changes (by Carlton Gibson):
* keywords: => autocomplete * version: 2.1 => master * stage: Unreviewed => Accepted Comment: OK, this is a gnarly one but I'm going to Accept it as a possible optimization. The **extra** queries are generated when rendering the `optgroups` for the widgets. django-autocomplete-light (DAL) [https://github.com/yourlabs/django- autocomplete- light/blob/230c9a119d24ef969a39c4fbd28207714f26ca58/src/dal/widgets.py#L132 excludes unselected self.choices before determining the options to render], i.e. it only initially renders the selected option. Where the selected option is **just** the foreign key value that we already selected for the admin this query can be eliminated. {{{ SELECT "inl_child2"."id", "inl_child2"."key_id", "inl_child2"."boolean", "inl_child2"."child_key_id" FROM "inl_child2" INNER JOIN "inl_child3_child_keys" ON ("inl_child2"."id" = "inl_child3_child_keys"."child2_id") WHERE "inl_child3_child_keys"."child3_id" = 1 }}} Looks to already cover in this case: {{{ SELECT "inl_child2"."id", "inl_child2"."key_id", "inl_child2"."boolean", "inl_child2"."child_key_id" FROM "inl_child2" WHERE "inl_child2"."id" IN (2) }}} (Since the FK points to child2.id = 2 in this case.) Forcing evaluation of the [https://github.com/yourlabs/django- autocomplete- light/blob/230c9a119d24ef969a39c4fbd28207714f26ca58/src/dal/widgets.py#L186 temporarily reduced queryset (here)] causes the query count to match that observed in Django's own autocomplete, since we apply no such optimization. (i.e All choices are required in `optgroups()` in Django's version.) Thus in theory there's a gain to be had here. Thanks for the report George. Fancy working on a patch? 🙂 -- Ticket URL: <https://code.djangoproject.com/ticket/30256#comment:7> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To post to this group, send email to django-updates@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/066.2671a17560c0e27e3b95894e0610d799%40djangoproject.com. For more options, visit https://groups.google.com/d/optout.