﻿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
30256	autocomplete_fields cause one or two extra queries for each field wth foreign key or many to many relation	George Tantiras	nobody	"The following model:

models.py
{{{#!python

class Child3(models.Model):
    key = models.ForeignKey(Master, on_delete=models.PROTECT)
    child_keys = models.ManyToManyField(Child2)
    boolean = models.BooleanField()

}}}

admin.py

{{{#!python

@admin.register(models.Child3)
class Child3Admin(admin.ModelAdmin):
    search_fields = ('id', )
    autocomplete_fields = ('key', 'child_keys')
    # form = forms.Child3Form  # Uncomment to enable django-autocomplete-light

}}}

When visiting the url of instance with id 1: http://127.0.0.1:8000/admin/inl/child3/1/change/

The queries count varies as follows:

no autocomplete feature: 3 queries
with autocomplete_fields enabled: 6 queries
with django-autocomplete-light enabled: 3 queries


I have not calculated the contentype query that sometimes appears and sometimes not. 

When the above model is used as inline to another model the queries for each related instance accumulate.

I have uploaded the [https://github.com/raratiru/autobug  autobug app ] which illustrates the above using 4 related models using foreign keys and many to many fields.
"	Cleanup/optimization	closed	contrib.admin	dev	Normal	fixed	autocomplete	Johannes Maron	Accepted	0	0	0	0	0	0
