Search code examples
pythondjangooverridingmanytomanyfield

django manytomanyfield .add() method


Suppose i have :

class Album(models.Model):
    photos = models.ManyToManyField('myapp.Photo')
    photo_count = models.IntegerField(default = 0)

class Photo(models.Model):
    photo = models.ImageField(upload_to = 'blahblah')

What is want is, everytime i call .add() method, increment the photo_count on Album class, so i'm thinking to override .add() method. The problem is, i can't import the .add()'s class since it is inside a method, so it is like def->class->def. So is there anyway to override .add() ? Or there is a better way to do this?


Solution

  • You can use django's signals and write a signal handler that will increment the counter using the m2m_changed signal:

    https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed