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?
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.
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).
ManyToMany field has some methods that you can call: add(Object) remove(Object) clear() this one is for removing all objects.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With