Home > database >  Get count of second-degree foreign-key entities in Django
Get count of second-degree foreign-key entities in Django

Time:01-06

We have a data model with three basic models:

  • Group
  • Activity
  • Participant (User model)
class Group(models.Model):
    name = models.CharField(max_length=255)

class Activity(models.Model):
    participants = models.ManyToManyField(
        to=settings.AUTH_USER_MODEL
    )
    group = models.ForeignKey(to=Group, reverse_name="activities")

I want to know how many times people participated in group activities, so I would like to count participants for all activities regardless of uniqueness.

How can I sum the counts of all participants for all activities related to a given group?

example data set with aggregation

CodePudding user response:

I am not sure if I have understood the question correctly (judging from the diagram I think so). This query would return the sum of the number of participants (not distinct) of all the activities of group 1:

User.objects.filter(activity__group_id=1).count()
  •  Tags:  
  • Related