def basequeryset(reportclass, request, args, kwargs): if args and args[0]: base = FlowPlan.objects.filter(thebuffer__exact=args[0]) else: base = FlowPlan.objects return base.select_related() \ .extra(select={ 'operation_in': "select name from operation where out_operationplan.operation = operation.name", 'demand': ("select %s(q || ' : ' || d, ', ') from (" "select round(sum(quantity)) as q, demand as d " "from out_demandpegging " "where out_demandpegging.operationplan = out_flowplan.operationplan_id " "group by demand order by 1 desc, 2) peg" % string_agg()) })