'Django DRF group by parent of parent with one-to-one relationships

I'm new to Django, and the jump from SQL to the Django DRF/ORM has been fun but challenging. I'm struggling to understand how to get a sum of a field of a class while grouping by it's parent's parent:

models.py :

class Plan(models.Model):
    plan_id = models.BigAutoField(primary_key=True)
    date = models.DateField()
    quantity = models.DecimalField(
        max_digits=18, decimal_places=0, blank=True, null=True)
    plan_type = models.CharField(max_length=50)
    plan_line = models.ForeignKey('PlanLine', models.CASCADE)


class PlanLine(models.Model):
    plan_line_id = models.BigAutoField(primary_key=True)
    year_period = models.CharField(max_length=50)
    line = models.ForeignKey('Line', models.CASCADE, blank=True, null=True)
    parent_assembly = models.ForeignKey(
        'ParentAssembly', models.CASCADE, blank=True, null=True)


class Line(models.Model):
    line_id = models.BigAutoField(primary_key=True)
    line_name = models.CharField(max_length=50)
    factory = models.ForeignKey(
        'Factory', models.DO_NOTHING, blank=True, null=True)


class Factory(models.Model):
    factory_id = models.BigAutoField(primary_key=True)
    factory_name = models.CharField(max_length=50)

I'm trying to get Sum(Plan.quantity), group by Factory.

I think I need to use the following, but don't understand how to get to Factory in this manor: Plan.objects.value(**Factory**).annotate(qty=Sum('quantity'))



Solution 1:[1]

This worked for me, I was a little unclear as to the magic behind the __ variables because it's so easy and dynamic to use:

Plan.objects.value('plan_line__line__factory').annotate(qty=Sum('quantity')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SCrawford