Post_save signal on the m2m field

I have a pretty typical article model, with a ratio of m2m to Tag model. I want to save the amount of use of each tag, I think that the best way would be to denormalize the counter field on the tag model and update it every time you save the article. How can I do this, or maybe the best way?

+6
python django django-signals
source share
2 answers

You can do this by creating an intermediate model for M2M relationships and use it as your hook for post_save and post_delete to update the denormalized column in the Article table.

For example, I do this for the favorite Question counts in soclone , where User has an M2M relationship with Question s:

 from django.contrib.auth.models import User from django.db import connection, models, transaction from django.db.models.signals import post_delete, post_save class Question(models.Model): # ... favourite_count = models.PositiveIntegerField(default=0) class FavouriteQuestion(models.Model): question = models.ForeignKey(Question) user = models.ForeignKey(User) def update_question_favourite_count(instance, **kwargs): """ Updates the favourite count for the Question related to the given FavouriteQuestion. """ if kwargs.get('raw', False): return cursor = connection.cursor() cursor.execute( 'UPDATE soclone_question SET favourite_count = (' 'SELECT COUNT(*) from soclone_favouritequestion ' 'WHERE soclone_favouritequestion.question_id = soclone_question.id' ') ' 'WHERE id = %s', [instance.question_id]) transaction.commit_unless_managed() post_save.connect(update_question_favourite_count, sender=FavouriteQuestion) post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion) # Very, very naughty User.add_to_class('favourite_questions', models.ManyToManyField(Question, through=FavouriteQuestion, related_name='favourited_by')) 

There was a little discussion on the django-developers mailing list about introducing a declarative denormalization declaration tool to avoid having to write code as above:

+2
source share
+3
source share

All Articles