Landmaster
Landmaster

Reputation: 1053

Django | Aggregate Values from Foreign Key

I have two databases, A and B.

B contains a ForeignKey to A.

When I do B.objects.filter(a_id=3).values('bags').count(), I get the number I want, Y.

What is the set of commands I need in order to add this number, Y, as an annotation into database A?

Ideally, this would be an annotate type of command.

The models look like:

class A(models.Model):
    name = models.CharField(max_length=150)

class B(models.Model):
    name = models.CharField(max_length=150)
    a_id = models.ForeignKey(A, on_delete=models.CASCADE)
    bags = models.ManyToManyField(Bags)

class Bags(models.Model):
    name = models.CharField(max_length=150)

Upvotes: 0

Views: 1150

Answers (2)

JPG
JPG

Reputation: 88499

from django.db.models import Count

A.objects.annotate(Y=Count('b__bags'))

Upvotes: 1

neverwalkaloner
neverwalkaloner

Reputation: 47354

Try to use b__bags lookup in annotation:

from django.db.models import Count
A.objects.annotate(bags_count=Count('b__bags'))

Upvotes: 2

Related Questions