How to annotate the number of times a related field appears for the parent [Django]
I've got 2 classes:
class Agent(models.Model):
pass
class Client(models.Model):
agent = models.ForeignKey(
"agents.Agent",
on_delete=models.SET_NULL,
)
connected = models.BooleanField(
default=False,
)
I know that if connected was an integer, I could use Sum like this:
Agent.objects.all().annotate(
Sum("client__connected"),
)
But how would I get the count based on the value of the related field?
I've also tried:
Agent.objects.all().annotate(
connected=Count(
"connected",
filter=Q(client__connected=True),
)
)
But this just gives me the error:
An exception of type FieldError. Arguments: ("Cannot resolve keyword 'connected' into field.