如何减少django admin中的重复SQL查询

时间:2019-02-15 11:38:02

标签: django django-admin

我有一个model,它是许多其他型号的ForeginKey。我在TabularInline中将它们定义为ModelAdmin。看起来像这样:

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']

它正在进行764个查询,包括757个相似和468个重复。我正在尝试了解如何使用select_related来减少这种情况,但我所做的一切似乎都没有任何效果。

任何人都可以给我一些指导。谢谢

**编辑** 内联已添加

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'

1 个答案:

答案 0 :(得分:1)

您没有显示重复查询的示例。但是,我可以看到您的HouseSelectionInline列表正在显示相关selection对象的信息。您应该重写get_queryset才能使用select_related在原始查询中获得该关系:

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

类似地,对于HouseWork,您应该使用prefetch_related来获取punches的数据,因为它是相反的关系:

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'

我看不到HouseSpecification.specificationHouseWork.delay是什么,但是如果它们也是FK,则应该执行类似的操作。