﻿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
29985	Add ModelAdmin.list_prefetch_related	Hidde Bultsma	Hidde Bultsma	"Currently, applying `prefetch_related` to a ModelAdmin's queryset is a relatively simple operation. Take the following example:

{{{#!python
class CollectionAdmin(admin.ModelAdmin):
    list_display = ('name', 'item_count')
    inlines = (ItemInline,)

    def item_count(self, obj):
        return obj.items.count()

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.prefetch_related('items')
}}}

With an override of `get_queryset` we can apply `prefetch_related`.

While this massively reduces the query count in the list view, it also introduces an extra redundant query in the change view. Both the prefetch and the ItemInline from this example will essentially execute the same query:

[[Image(https://i.imgur.com/A9C4Sst.png)]]

This prefetch was really only needed in the list view to show the item count per collection. But because `get_queryset` is called from both the list and change view, the prefetch was also applied in both.

=== New option ModelAdmin.list_prefetch_related

With a `list_prefetch_related` option in the ModelAdmin, prefetches could be more specifically targeted to the list view, preventing undesired prefetches in the change view.

This option should allow a list of lookups or None as value; the possible parameters of `prefetch_related`. It should be possible to set the value dynamically using a `get_list_prefetch_related` hook.

The example could be reimplemented with this option to the following code:

{{{#!python
class CollectionAdmin(admin.ModelAdmin):
    list_display = ('name', 'item_count')
    list_prefetch_related = ('items',)
    inlines = (ItemInline,)

    def item_count(self, obj):
        return obj.items.count()
}}}"	New feature	closed	contrib.admin	dev	Normal	wontfix	admin ModelAdmin prefetch_related		Unreviewed	1	0	0	0	0	0
