Django:在信号中获取M2M相关对象 [英] Django: Getting m2m related objects in signals

查看:88
本文介绍了Django:在信号中获取M2M相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点想看到类似的问题( Django访问ManyToMany字段,但仍然看不到如何获取更新的相关对象列表。

I was kind of trying to see similar questions (Django accessing ManyToMany fields from post_save signal), but still don't see how to get the updated related objects list.

例如我有以下模型

class User(models.Model):
    username = models.CharField

class Blog(models.Model):
    user = models.ManyToManyField('User')

现在,我要通过django admin将用户添加到给定的博客中。

Now I am adding a user to a given blog, via django admin.

所以我希望下面的信号将打印所有新用户(我刚刚添加的)...但是...我得到了所有的旧列表时间:(

So I expect that the signal below, will print all new users (which I have just added)... but... I am getting the old list all the time :(

@receiver(m2m_changed, sender=Blog.users.through)
def blog_users_change(sender, instance, **kwargs):
     print instance.users.all()

最后一行给出用户的旧列表 instance.users.all()。例如,此处添加的用户不会得到体现。

The last line gives old list of users instance.users.all(). E.g. users added here are not reflected.

推荐答案

m2m_changed 信号在保存/更新过程的多个阶段被触发,并且有一个操作参数,告诉您它处于哪个阶段。来自文档

m2m_changed signals are fired at several stages in the save/update process, and there is an action argument supplied to the signal handler that tells you what stage it is in. From the documentation:


动作

一个字符串,指示在关系上完成的更新的类型。以下之一:

A string indicating the type of update that is done on the relation. This can be one of the following:

pre_add
在将一个或多个对象添加到关系之前发送。

"pre_add" Sent before one or more objects are added to the relation.

post_add
在将一个或多个对象添加到关系后发送。

"post_add" Sent after one or more objects are added to the relation.

pre_remove
在从关系中删除一个或多个对象之前发送。

"pre_remove" Sent before one or more objects are removed from the relation.

后删除
从关系中删除一个或多个对象后发送。

"post_remove" Sent after one or more objects are removed from the relation.

pre_clear
在关系清除之前发送。

"pre_clear" Sent before the relation is cleared.

post_clear
关系清除后发送。

"post_clear" Sent after the relation is cleared.

如果捕捉到 pre_remove 操作,则将获得所有之前对象已从关系中删除。这就是为什么您看到的用户列表似乎没有变化的原因。

If you catch the pre_remove action then you will get all the objects before some have been removed from the relationship. That is why you are seeing an apparently unchanged list of users.

您的代码需要先检查操作,然后再确定该怎么办。例如:

Your code needs to check the action before deciding what to do. For example:

@receiver(m2m_changed, sender=Blog.users.through)
def blog_users_change(sender, instance, action, **kwargs):
    if action == 'pre_remove':
         # This will give you the users BEFORE any removals have happened
         print instance.users.all()
    elif action == 'post_remove':
         # This will give you the users AFTER any removals have happened
         print instance.users.all()

这篇关于Django:在信号中获取M2M相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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