django manytomanyfield .add()方法 [英] django manytomanyfield .add() method
问题描述
假设我有:
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')
想要的是,每次我调用.add()方法,增加 photo_count
on Album
class,所以我正在考虑重写.add()方法。问题是,我无法导入 .add()
的类,因为它在一个方法中,所以它像 def-> ;类 - > DEF
。那么有没有办法覆盖 .add()
?还是有更好的方法呢?
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?
推荐答案
你可以使用django的信号并写一个信号处理程序,它将使用 m2m_changed
信号:
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
这篇关于django manytomanyfield .add()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!