Django从post_save信号访问ManyToMany字段 [英] Django accessing ManyToMany fields from post_save signal

查看:122
本文介绍了Django从post_save信号访问ManyToMany字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django模型,我想修改对象权限或保存后。我已经尝试了一些解决方案,并且 post_save 信号似乎是我想要做的最好的候选人:

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()))

在这种情况下,当创建项目时,信号会触发,我看到标题,但是是空的列表为 assigned_to 字段。

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.

如何在保存之后访问保存的 assigned_to 数据?

How can I access the saved assigned_to data following save?

任何帮助不胜感激。

推荐答案

你不会去。在保存实例后,保存M2M,因此在所有m2m更新中将不会有任何记录。更多的问题(即使你解决了),你仍然在一个交易,查询数据库将不会得到你的m2m与适当的状态无论如何。

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.

解决方案将钩入 m2m_changed 信号而不是 post_save

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

https://docs.djangoproject.com/en/dev/ref/signals/# m2m更改

您的发件人将是 Project.assigned_to.through

这篇关于Django从post_save信号访问ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆