Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
Santana Avatar asked Nov 10 '12 10:11

Santana


People also ask

How do I add to ManyToManyField in Django?

How to Add an Object to a ManyToManyField. Now let's see how to add an object to a ManyToManyField in Django. To do so, Django has a built-in function, add(), which allows us to do so. This would be done in the views.py file.

How do you add a many-to-many relationship?

For those relationships, you simply connect the appropriate fields with a line. To create many-to-many relationships, you need to create a new table to connect the other two. This new table is called an intermediate table (or sometimes a linking or junction table).

How do I get rid of many to many fields in Django?

ManyToMany field has some methods that you can call: add(Object) remove(Object) clear() this one is for removing all objects.

How do I create a one to many relationship in Django?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).


1 Answers

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

like image 170
Timmy O'Mahony Avatar answered Sep 22 '22 05:09

Timmy O'Mahony