Search code examples
pythondjangomanytomanyfield

Count values in ManyToManyField - Django


i need some help. I have a model "Event" with manytomanyfield "users":

class Event(models.Model):
    name = models.CharField(max_length=26)
    description = models.CharField(max_length=200)
    date = models.DateField()
    user = models.ForeignKey(User)
    users = models.ManyToManyField(User, related_name="event", blank=True)
    image = models.ImageField(
        upload_to='images/',
        default='images/default.png'
    )

So, manytomany intermediary table has two fields: user_id and event_id. How to count how many event_id = 1 or event_id = 2... are in this table? Thanks


Solution

  • All you'd need is the below model for Event:

    class Event(models.Model):
            name = models.CharField(max_length=26)
            description = models.CharField(max_length=200)
            date = models.DateField()
            user = models.ManyToMany(User, related_name="events")
            image = models.ImageField(
                upload_to='images/',
                default='images/default.png'
            )
    

    And then from a object of User (say logged_in_user) you can make calls such as logged_in_user.events.all() to get all the events. Or if you just need event id's then logged_in_user.events.values_list('id', flat=True)

    If you just want a count, then it should be logged_in_user.events.count(). As you can see, you can treat events the same as any other manager (like objects on your user model).

    If you need the count of users participating in a single event with event_id. User this: Event.objects.get(id=event_id).users.count()