Dennis
Dennis

Reputation: 99

Python Django Annotations over multiple relationships

I have a question On Django annotations. Here is my model:

class Asset(models.Model):
    security = models.ForeignKey(Security, on_delete=models.CASCADE, blank=False)


class Batch(models.Model):
    fk_asset = models.ForeignKey(Asset, on_delete=models.CASCADE, blank=False)


class BatchPosition(models.Model):
    fk_batch = models.ForeignKey(Batch, on_delete=models.CASCADE)
    quantity = models.DecimalField(max_digits=14, decimal_places=2, blank=False)

In my view I would like to annotate the total Sum of Batchposition->quantity to the Asset

I tried things like

Asset.objects.annotate(Sum("batch")).annotate(Sum("batchposition__quantity"))

...but can't get it to work. What am I doing wrong here? Is it finally possible to achieve this?

Upvotes: 0

Views: 54

Answers (1)

PTomasz
PTomasz

Reputation: 1718

You don't need sum of batches of each asset.

To get sum of quantity of BatchPosition of each Batch on Asset you can follow relationship directly using '__'. So if we set related_name to batches on fk_asset in Batch model and batch_positions on fk_batch in BatchPosition model we can annotate sum like that:

Asset.objects.annotate(batch_positions_sum=Sum('batches__batch_positions__quantity'))

Looks like you could use some more materials regarding Django ORM DB aggregations

Django Aggregation

Upvotes: 1

Related Questions