Search code examples
pythondjangodjango-modelsdjango-signals

Django manytomany signals?


Let's say I have such model

class Event(models.Model)
    users_count = models.IntegerField(default=0)
    users = models.ManyToManyField(User)

How would you recommend to update users_count value if Event add/delete some users ?


Solution

  • If possible in your case, you could introduce Participation model which would join Event and User:

    class Participation(models.Model):
        user = models.ForeignKey(User)
        event = models.ForeignKey(Event)
    
    class Event(models.Model):
        users = models.ManyToManyField(User, through='Participation')
    

    And handle pre_save signal sent by Participation to update instance.event counts. It would simplify handling of m2m significantly. And in most cases, it turns out later on that some logic and data fits best in the middle model. If that's not your case, try a custom solution (you should not have many code paths adding Users to Events anyway).