I overwrote get_queryset and get the results I require. The problem is however that the page takes quite long to load. Upon checking the SQL debugger, it became apparent that two the same queries are executed and a third similar query. Does anyone have a reason why and how this could be avoided?
Thank you kindly in advance.
SQL:
QUERY TIMELINE TIME (MS) ACTION
+
SELECT ••• FROM "django_session" WHERE ("django_session"."expire_date" > '''2021-07-13 20:49:27.015683''' AND "django_session"."session_key" = '''26huoisce3p4p3ef0f37vysjzo55uu3h''') LIMIT 21
1.18
Sel Expl
+
SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '1' LIMIT 21
0.58
Sel Expl
+
SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id") subquery
2 similar queries. Duplicated 2 times. 1625.29
Sel Expl
+
SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id") subquery
2 similar queries. Duplicated 2 times. 1449.67
Sel Expl
+
SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id", "inventory_product"."ean", "inventory_product"."hscode_id" ORDER BY "return_rate" DESC, "inventory_product"."id" DESC LIMIT 100
1387.94
Sel Expl```
PYTHON/DJANGO:
```@admin.register(ProductProxy)
class ProductProxyAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(ProductProxyAdmin, self).get_queryset(request)
qs = qs.annotate(
total_sales=Coalesce(Sum('invoice_line__invoiced_quantity',
filter=Q(invoice_line__invoice_linetype__id=3)),0.0),
total_returns=Coalesce(Sum('invoice_line__invoiced_quantity',
filter=Q(invoice_line__invoice_linetype__id=7)), 0.0)) \
.annotate(
return_rate=ExpressionWrapper(F('total_returns')* 1.0 /F('total_sales'),
output_field=DecimalField(decimal_places=2))
).order_by('-return_rate')
return qs```