保存后,ManyToMany关系无法立即更新的问题 [英] Issue with ManyToMany Relationships not updating immediately after save

查看:98
本文介绍了保存后,ManyToMany关系无法立即更新的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了很多对多关系问题,当我保存模型(通过管理员)并尝试在附加到<$的
函数中使用新值时,没有更新模型中的
c $ c> post_save 信号或在
save_model 内,关联的 AdminModel
我尝试通过使用带有ID的
get函数在这些函数中重新加载对象。.但是它仍然具有旧值。

I'm having issues with ManytoMany Relationships that are not updating in a model when I save it (via the admin) and try to use the new value within a function attached to the post_save signal or within the save_model of the associated AdminModel. I've tried to reload the object within those functions by using the get function with the id.. but it still has the old values.

这是交易问题吗?
交易结束时会发出信号吗?

Is this a transaction issue? Is there a signal thrown when the transaction ends?

谢谢

推荐答案

通过管理表单保存模型时,这不是原子事务。首先保存主要对象(以确保它具有PK),然后 清除 清除M2M,并将新值设置为表单中的任何值。因此,如果您位于主要对象的save()中,那么您将处于尚未更新M2M的机会之窗中。实际上,如果您尝试对M2M做某事,则clear()会清除更改。大约一年前,我遇到了这个问题。

When you save a model via admin forms it's not an atomic transaction. The main object gets saved first (to make sure it has a PK), then the M2M is cleared and the new values set to whatever came out of the form. So if you are in the save() of the main object you are in a window of opportunity where the M2M hasn't been updated yet. In fact, if you try to do something to the M2M, the change will get wiped out by the clear(). I ran into this about a year ago.

与ORM重构之前的代码相比,代码有所变化,但归结为中的代码。 django.db.models.fields.ManyRelatedObjectsDescriptor ReverseManyRelatedObjectsDescriptor 。查看他们的__set __()方法,您会看到 manager.clear();。 manager.add(* value) clear()complete会清除该表中当前主对象的所有M2M引用。然后,add()设置新值。

The code has changed somewhat from the pre-ORM refactor days, but it boils down to code in django.db.models.fields.ManyRelatedObjectsDescriptor and ReverseManyRelatedObjectsDescriptor. Look at their __set__() methods and you'll see manager.clear(); manager.add(*value) That clear() complete cleans out any M2M references for the current main object in that table. The add() then sets the new values.

因此回答您的问题:是的,这是一个事务问题。

So to answer your question: yes, this is a transaction issue.

交易结束时是否发出信号?什么都没有,但请继续阅读:

Is there a signal thrown when the transaction ends? Nothing official, but read on:

有一个相关的线程,而MonkeyPatching是提出的一种方法。 Grégoire为此发布了一个MonkeyPatch 。我没有尝试过,但是看起来应该可以。

There was a related thread a few months ago and MonkeyPatching was one method proposed. Grégoire posted a MonkeyPatch for this. I haven't tried it, but it looks like it should work.

这篇关于保存后,ManyToMany关系无法立即更新的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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