gpt4 book ai didi

python - Django:在信号中获取 m2m 相关对象

转载 作者:行者123 更新时间:2023-12-02 04:09:27 26 4
gpt4 key购买 nike

我试图查看类似的问题( Django accessing ManyToMany fields from post_save signal ),但仍然不知道如何获取更新的相关对象列表。

例如我有以下型号

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

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

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

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

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

最后一行给出了旧的用户列表instance.users.all()。例如。此处添加的用户不会反射(reflect)出来。

最佳答案

m2m_changed 信号在保存/更新过程中的多个阶段触发,并且向信号处理程序提供一个 action 参数,告诉您它处于哪个阶段.来自documentation :

action

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

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

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

"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" Sent before the relation is cleared.

"post_clear" Sent after the relation is cleared.

如果您捕获了 pre_remove 操作,那么您将获得在某些对象从关系中删除之前的所有对象。这就是为什么您看到的用户列表显然没有变化。

您的代码需要在决定做什么之前检查操作。例如:

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

关于python - Django:在信号中获取 m2m 相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37528922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com