问题
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