Django admin terrible performance get_form queryset filter when adding order_by

时间秒杀一切 提交于 2020-04-30 16:35:38

问题


I'm encountering some terrible performance issues when trying to filter a forms queryset.

I'm trying to filter a Model where a relationship already exists.

The code is successful.

But my queryset is not ordered.

The moment I change to form.base_fields['sharepoint_mandate'].queryset = Sharepoint_Mandate.objects.filter(mandate_mapping_2__isnull=True).order_by('product_name') the query now takes 25 seconds

Please help

models.py

class Mandate_Mapping_2(Trackable):
    mandate_mapping_id = models.AutoField(primary_key=True)  
    sharepoint_mandate = models.ForeignKey(Sharepoint_Mandate, on_delete=models.CASCADE)  
    sharepoint_product = models.ForeignKey(Sharepoint_Product, on_delete=models.CASCADE)  

admin.py

@admin.register(Mandate_Mapping_2)
class ChampMandateMapping2Admin(admin.ModelAdmin): 
    list_display =  ['sharepoint_mandate', 'sharepoint_product', 'approved']

    def get_form(self, request, obj=None, **kwargs):        
        form = super(ChampMandateMapping2Admin, self).get_form(request, obj, **kwargs)

        if 'change' in kwargs:
            if not kwargs['change']:
                form.base_fields['sharepoint_mandate'].queryset = Sharepoint_Mandate.objects.filter(mandate_mapping_2__isnull=True)
        return form

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'sharepoint_product', 
            'sharepoint_mandate',
        )

回答1:


When checking the existence of a Mandate_Mapping_2 for a Sharepoint_Mandate you are making an extra query for nothing. You can use the column name attribute.

Sharepoint_Mandate.objects.filter(mandate_mapping_2_id=None).order_by('product_name')

You can look at "Use foreign key values directly" part in Django database access optimization docs



来源:https://stackoverflow.com/questions/54777663/django-admin-terrible-performance-get-form-queryset-filter-when-adding-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!