﻿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
29294	ModelAdmin.raw_id_fields should be included in select_related() by change_view and used by raw id widget	Yurii Zolot'ko	nobody	"Consider model A having many ForeignKey relationships to other models B,C,D...Z (common case in many applications).
ModelAdmin has `raw_id_fields` optimization option to avoid querying full contents of B...Z tables every time.
However in some cases this optimization is not enough as it still invokes several queries to B... tables to fetch single row from every of them to display `__str__` and url of related object next to raw input field when admin's change_view is opened for single object.
So when there are 3 ForeignKeys there will at least 4 queries per request (1 for object itself, 3 for every ForeignKey). When there are 10 ForeignKeys there will be 11 queries per request and so on resulting in very high response time for complex objects even using raw_id_fields.
It looks like this problem is not possible to avoid now. I've tried to override get_queryset() method of ModelAdmin to select_related() raw_id_fields like this:

{{{
class ObjectAdmin(admin.ModelAdmin):
    raw_id_fields = (
        'field1', 'field2', ...)

    def get_queryset(self, request):
        qs = admin.ModelAdmin.get_queryset(self, request)
        return qs.select_related(*self.raw_id_fields)
}}}

But django.contrib.admin.widgets.ForeignKeyRawIdWidget.label_and_url_for_value() still invokes separate query for every ForeignKey relationship instead of getting it from attribute of already fetched object resulting in high response times of admin interface impossible to improve.

It would be significant performance improvement if ModelAdmin could select_related() `raw_id_fields` by default and ForeignKeyRawIdWidget wouldn't do extra queries for every related object when all necessary data is already present."	Cleanup/optimization	closed	contrib.admin	1.11	Normal	wontfix			Unreviewed	0	0	0	0	0	0
