Facing issue in Group By in 3 levels of table.

Models:

  1. Employee - name, email
  2. CuttingJob - employee (ForeignKey), count
  3. OrderCuttingDetail - product_name, amount

I want to show the employee wise cutting count and it’s amount.

employees = Employee.objects.annotate(
total_cutting_job_count=Sum(‘cutting_jobs__count’),
total_cutting_job_amount=ExpressionWrapper(F(‘total_cutting_job_count’) * F(‘cutting_jobs__order_cutting_detail__amount’), output_field=DecimalField()),
).all()

But while running this query, employees are duplicated. Need to group the records based on employee’s name.

Kindly suggest a solution for this.

What is the relationship between CuttingJob and OrderCuttingDetail?

@KenWhitesell

OrderCuttingDetail will have the pieces to be cut and it’s total count with per piece amount.

CuttingJob will have the employee’s per day’s cutting output details.

I’m asking in terms of the models. You don’t show any foreign keys relating OrderCuttingDetail to either of the other two models.