[Answered ]-How to call post_save signal after adding object to ManyToMany field on another model

1👍

You can work with the m2m_changed signal [Django-doc]:

from django.db.models.signals import m2m_changed

@receiver(m2m_changed, sender=Post.comments.through)
def comments_changed(sender, instance, action, **kwargs):
    if action in ('post_add', 'post_remove', 'post_clear'):
        cache.set(f'post_comment_count_{instance.pk}', instance.comments.count())

That being said, signals are typically anti-patterns. A lot of ORM calls can circumvent signals, and it makes saving objects less predictable. Therefore it might be better to simply encapsulate the logic in a view, and call that function in views where you edit the comments.

Leave a comment