django manytomanyfield .add() method

回眸只為那壹抹淺笑 提交于 2019-12-19 02:52:08

问题


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?


回答1:


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




回答2:


Probably the simplest option is to skip signals, drop the photo_count field entirely and call [album].photos.count() anywhere you would have used [album].photo_count.

You could also define a property on Album as follows:

class Album(models.Model):
    photos = models.ManyToManyField('myapp.Photo')

    @property
    def photo_count(self):
        return self.photos.count()

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

The downside of both options is they makes it harder to search / sort based on the number of photos. They also don't store the count in the database. (That might be import if you have some non-Django application which is interacting with the same DB.) If you think you'll want to do those sorts of searches via Django, look into Django annotations.

This is simpler than dealing with signals, but probably still overkill.



来源:https://stackoverflow.com/questions/13321398/django-manytomanyfield-add-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!