45

I have a Django model and I want to modify the object permissions on or just after save. I have tried a few solutions and the post_save signal seemed the best candidate for what I want to do:

    class Project(models.Model):
        title = models.CharField(max_length=755, default='default')
        assigned_to = models.ManyToManyField(
            User, default=None, blank=True, null=True
        )
        created_by = models.ForeignKey(
            User,
            related_name="%(app_label)s_%(class)s_related"
        )


    @receiver(post_save, sender=Project)
    def assign_project_perms(sender, instance, **kwargs):
        print("instance title: "+str(instance.title))
        print("instance assigned_to: "+str(instance.assigned_to.all()))

In this case, when a Project is created, the signal fires and I see the title, but an empty list for the assigned_to field.

How can I access the saved assigned_to data following save?

halfer
  • 19,471
  • 17
  • 87
  • 173
Darwin Tech
  • 17,419
  • 37
  • 105
  • 178

3 Answers3

66

You're not going to. M2Ms are saved after instances are saved and thus there won't be any record at all of the m2m updates. Further issues (even if you solve that) are that you're still in a transaction and querying the DB won't get you m2m with proper states anyways.

The solution is to hook into the m2m_changed signal instead of post_save.

https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed

Your sender then would be Project.assigned_to.through

Yuji 'Tomita' Tomita
  • 110,403
  • 28
  • 276
  • 239
  • I have the same issue with a ForeignKey, but apparently there's no signal for that? – Hendrik Sep 23 '18 at 15:01
  • +1 for identifying the sender (many-to-many_field.through). It is handy in case the m2m relation is not defined with an explicit model. – mrdaliri Jul 06 '20 at 03:55
  • It seems that `m2m_changed` is not fired in the admin. Is that correct? Perhaps relevant: https://code.djangoproject.com/ticket/16073 – Dan Swain Sep 25 '20 at 14:29
29

If your m2m can be empty (blank=True) you are in a little trouble with m2m_changed, because m2m_changed doesn't fire if m2m wasn't set. You can solve this issue by using post_save and m2m_changed at the same time. But there is one big disadvantage with this method - your code will be executed twice if m2m field isn't empty.

So, you can use transaction's on_commit (Django 1.9+)

Django provides the on_commit() function to register callback functions that should be executed after a transaction is successfully committed.

from django.db import transaction

def on_transaction_commit(func):
    def inner(*args, **kwargs):
        transaction.on_commit(lambda: func(*args, **kwargs))

    return inner

@receiver(post_save, sender=SomeModel)
@on_transaction_commit
def my_ultimate_func(sender, **kwargs):
    # Do things here

Important note: this approach works only if your code calls save(). post_save signal doesn't fire at all in cases when you call only instance.m2m.add() or instance.m2m.set().

Mark Mishyn
  • 3,471
  • 2
  • 23
  • 25
  • 1
    I tried using on_commit with post save (the last code you wrote), and the changes in the m2m models still aren't applied. – Daniel Apr 06 '20 at 20:50
  • @Daniel probably your code doesn't call `save()` at all and that's why `post_save` signal doesn't work. – Mark Mishyn Apr 08 '20 at 07:13
0

Use transaction on commit!

from django.db import transaction

@receiver(post_save, sender=Project)
def assign_project_perms(sender, instance, **kwargs):
    transaction.on_commit(lambda: print("instance assigned_to: "+str(instance.assigned_to.all())))