0
from django.db import models

class Reporter(models.Model):
    pass

class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, null=True)

With the models above, what signal should I listen to if I want to know when an article is added to a reporter?

>>> new_article = Article()
>>> new_reporter = Reporter()
>>> new_reporter.article_set.add(new_article)

I've tried both m2m_changed and post_save but neither works

from django.db.models.signals import m2m_changed, post_save
from django.dispatch import receiver

@receiver(m2m_changed)
def m2m_add(sender, instance, **kwargs):
    print "m2m_add triggered!"

@receiver(post_save)
def post_save_add(sender, instance, **kwargs):
    print "post_save_add triggered!"
Oskar Persson
  • 6,605
  • 15
  • 63
  • 124

1 Answers1

1

Connect to post_save of Article, but you have to call add with bulk=False:

new_reporter.article_set.add(new_article, bulk=False)
# will not use update and call save on article instance
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Tried that, nothing is triggered. – Oskar Persson Jan 24 '17 at 13:49
  • This works, however, isn't there anyway to listen for signals when calling `add` with `bulk=True`? – Oskar Persson Jan 24 '17 at 14:36
  • I don't think so. If you look at the [source code](https://github.com/django/django/blob/master/django/db/models/query.py) of `update`, there are no signals being send. – user2390182 Jan 24 '17 at 14:44
  • Could I write my own signal that triggers when adding to that specific field (with `bulk=True`)? – Oskar Persson Jan 24 '17 at 15:48
  • 1
    You can subclass `QuerySet`, override `update`, `bulk_create`, etc (call super() and send some signal). Then you have to give your model a custom manager which uses your custom queryset class. – user2390182 Jan 24 '17 at 17:13