For example I have this model:
class Parent(models.Model):
name = models.CharField(max_length=255)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
value = models.IntegerField()
p1 = Parent.objects.create(name='parent1')
c1 = Child.objects.create(parent=p1, value=1)
c2 = Child.objects.create(parent=p1, value=2)
c3 = Child.objects.create(parent=p1, value=3)
I want to make a subquery to behave like this:
parents_with_children = Parent.objects.annotate(
child_values=ArrayAgg('child__value', filter=F('child__parent_id') == F('id'))
)
for parent in parents_with_children:
print(f"Parent: {parent.name}, Child Values: {parent.child_values}")
OUTPUT: ## Parent: parent1, Child Values: [1, 2, 3]