HenryM
HenryM

Reputation: 5793

How do I reduce duplicate sql queries in django admin

I have a model which is a ForeginKey for a number of other models. I've defined these as TabularInlines within my ModelAdmin. It looks like this:

class HouseAdmin(admin.ModelAdmin):
    list_display = ['owner', 'get_house','number','street','city']
    list_filter = ['completed']
    readonly_fields = ['slug']
    inlines = [HouseWorkInline, HouseDocumentInline, HouseBudgetInline, HouseSelectionInline, \
        HouseSpecificationInline]
    actions = [send_schedule_emails]
    fieldsets = (
        (None, {'fields' : ('owner', 'number','street', 'city', 'start_date','completed')}),
    )
    search_fields = ['street','number','owner__username','city']

It is making 764 queries including 757 similar and 468 duplicates. I'm trying to understand how to reduce this using select_related but nothing I do seems to make any difference.

Can anyone give me some guidance please. Thank you

** EDIT ** Inlines added

class HouseSpecificationInline(admin.TabularInline):
    readonly_fields = ['get_specification']
    fields = ['get_specification','notes','order',]
    model = HouseSpecification
    extra = 0
    template = 'admin/houses/housespecification/edit_inline/tabular.html'

    def get_specification(self, obj):
        return mark_safe('%s' % (obj.specification))
    get_specification.short_description = 'Specification'

class HouseSelectionInline(admin.TabularInline):
    readonly_fields = ['get_selection','get_notes','get_external_link']
    fields = ['get_selection','get_notes','get_external_link','notes',]
    model = HouseSelection
    extra = 0
    can_order = True
    template = 'admin/houses/housework/edit_inline/tabular.html'

    def has_add_permission(self, request):
        return False

    def get_selection(self, obj):
        if obj.selection.f:
            return mark_safe('<a href="/core/download-pdf/%s">%s</a>' % (obj.selection.id, obj.selection))
        else :
            return mark_safe('%s' % (obj.selection))
    get_selection.short_description = 'Selection'

    def get_notes(self, obj):
        return obj.selection.notes

    def get_external_link(self, obj):
        if obj.selection.external_link:
            return mark_safe('<a target="_blank" href="%s">%s</a>' % (obj.selection.external_link, obj.selection.external_link))
        else: return ''
    get_external_link.short_description = "External Link"

class HouseBudgetInline(admin.TabularInline):
    model = HouseBudget
    extra = 1
    can_order = True
    show_change_link = True
    template = 'admin/houses/housebudget/edit_inline/tabular.html'

class HouseWorkInline(admin.TabularInline):
    readonly_fields =['activity','start_date','punches', 'get_delay']
    fields = ['activity','start_date','length','get_delay','note','contractor','date_completed','punches']
    model = HouseWork
    extra = 0
    can_delete = False
    show_change_link = True
    template = 'admin/houses/housework/edit_inline/tabular.html'

    def has_add_permission(self, request):
        return False

    def get_delay(self, obj):
        return obj.delay
    get_delay.short_description = 'Delay'        

    def punches(self, obj):
        text = ''
        for punch in obj.punch_set.filter(completed=False):
            text += punch.date_created.strftime("%m/%d/%Y") + ' - ' + punch.notes + '<br />'
        return mark_safe(text)
    punches.short_description = 'Punch List'

Upvotes: 2

Views: 1547

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You didn't show an example of your duplicate queries. However, I can see that your HouseSelectionInline list is displaying information of the related selection object. You should override get_queryset to use select_related to get that relationship in the original query:

class HouseSelectionInline(admin.TabularInline):
    ...
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('selection')

Similarly, for HouseWork, you should use prefetch_related to get the data for punches, because it is a reverse relationship:

class HouseWorkInline(admin.TabularInline):
    ...
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        punch_query = Punch.objects.filter(completed=False)
        incomplete_punches = Prefetch('punch_set', punch_query, to_attr='incomplete_punches')
        return qs.prefetch_related(incomplete_punches)

    def punches(self, obj):
        text = ''
        for punch in obj.incomplete_punches:
            text += punch.date_created.strftime("%m/%d/%Y") + ' - ' + punch.notes + '<br />'
        return mark_safe(text)
    punches.short_description = 'Punch List'

I can't see what HouseSpecification.specification and HouseWork.delay are, but if they are also FKs you should do something similar.

Upvotes: 2

Related Questions