问题与ManyToMany关系不保存后立即更新 [英] Issue with ManyToMany Relationships not updating inmediatly after save

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

问题描述

我遇到ManytoMany Relationships的问题,当我保存它(通过管理员)并且尝试使用附加到$的
函数中的新值时,模型中没有更新
c $ c> post_save 信号或$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ >。
我试图通过使用带有id的
get函数重新加载这些函数中的对象,但它仍然具有旧值。



<这是交易问题吗?
事务结束时是否有信号抛出?



谢谢,

解决方案

当您通过管理表单保存模型时,它不是原子事务。主要对象首先得到保存(以确保它具有PK),然后M2M被清除 ,新值将被设置为从形式出来的任何值。所以如果你在主要对象的save()中,你是在机会尚未更新的机会的窗口。事实上,如果您尝试对M2M做某些事情,则该更改将被clear()消除。一年前我遇到了这个问题。



代码从ORM前的重写日期有所改变,但它归结为 django.db.models.fields.ManyRelatedObjectsDescriptor ReverseManyRelatedObjectsDescriptor 。看看他们的__set __()方法,你会看到 manager.clear(); manager.add(* value) clear()完成清除该表中当前主对象的任何M2M引用。 add()然后设置新的值。



所以回答你的问题:是的,这是一个交易问题。



当事务结束时是否有信号抛出?没有任何官方,但阅读:



有一个相关的线程几个月前和MonkeyPatching是一种提出的方​​法。 Grégoire为此发布了一个MonkeyPatch 。我没有尝试过,但看起来应该可以正常工作。


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?

Thanks,

解决方案

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.

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:

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天全站免登陆