0

I need to notify users by email, when MyModel object is created. I need to let them know all attributes of this object including ManyToManyFields.

class MyModel(models.Model):
    charfield = CharField(...)
    manytomany = ManyToManyField('AnotherModel'....)

    def to_email(self):
        return self.charfield + '\n' + ','.join(self.manytomany.all())

    def notify_users(self):
        send_mail_to_all_users(message=self.to_email())

The first thing I tried was to override save function:

def save(self, **kwargs):
    created = not bool(self.pk)
    super(Dopyt, self).save(**kwargs)
    if created:
        self.notify_users()

Which doesn't work (manytomany appears to be empty QuerySet) probably because transaction haven't been commited yet.

So I tried post_save signal with same result - empty QuerySet.

I can't use m2mchanged signal because:

  1. manytomany can be None
  2. I need to notify users only if object was created, not when it's modified

Do you know how to solve this? Is there some elegant way?

Milano
  • 18,048
  • 37
  • 153
  • 353
  • I think you can use m2m_changed and use action. Check the doc (find for action): https://docs.djangoproject.com/en/2.0/ref/signals/ Many to Many relation are saved after object is save so post_save will never work. – Bulva May 06 '18 at 19:07
  • @Bulva but the problem is that even if object is created, the manytomany can be None so there will be no m2m_changed signal invoked. – Milano May 06 '18 at 19:09
  • 2
    You need to show exactly where you are setting the many-to-many values. Since those can't be set until the instance has an ID value, you must be doing it at some point after calling save anyway; so I don't understand why you can't do your notification then. – Daniel Roseman May 06 '18 at 19:09
  • @DanielRoseman I wanted to use it inside the model but it's a good idea. I use CreateView so I will call notify_users inside form_valid function. – Milano May 06 '18 at 19:12
  • @DanielRoseman But still, If I wanted to notify them even if object was created using admin or shell, your solution wouldn't work I think. – Milano May 06 '18 at 19:15
  • I don't think it's possible since when you create an object, the m2m will always be none. you can only add an instance to m2m after creating the object. so as you said **better call notify_users inside form_valid function** – Lemayzeur May 06 '18 at 19:17
  • The solution would be the same. If you're creating your item in the shell, you would need to save it and then add the many-to-many items. It is **not possible** to add m2m items before saving, no matter where you do it. – Daniel Roseman May 06 '18 at 19:21

0 Answers0