[Answer]-Django – adding a counter for every ManyToMany field added

1👍

You could have a field on the model and override the save method

class Invoice(models.Model):
    subject = models.ForeignKey(Subject)
    date = models.DateField(default=date.today())
    activities = models.ManyToManyField(Activity)
    activity_count = models.PositiveIntegerField(default=0)
    def save(self):
       self.activity_count = self.activities.count()
       super(Invoice, self).save()

Leave a comment