django db写入在管理站点中运行时不会立即发生 [英] django db writes not happening immediately when running in admin site

查看:157
本文介绍了django db写入在管理站点中运行时不会立即发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django应用程式中有这样的程式码片段

  def update_account(user_account,add_widget_count):
user_account.add_widgets(add_widget_count)
user_account.save()

notify_other_system_about_account_update(user_account)

当我运行这个作为我的应用程序的一部分,一切都很好。特别是,当我的其他系统(django外部)获得通知时,它检查数据库,并更新窗口小部件计数。



但是,当我从管理网站运行上面的代码时,有一个问题。当我的其他系统获取通知时,它不会在数据库中看到更新的值。我通过放置断点并检查数据库来确认,并且在调用.save()之后不会更新 - 在非管理网站调用中,当我在此断点期间检查时更新数据库。



django管理中间件是否会延迟或延迟od数据库写入?



更新



我甚至将呼叫转移到 notify_other_system_about_account_update(user_account )到我的UserAccount对象上的post_save信号处理程序。信号触发,但当我得到它。数据库在我的信号处理程序返回后的某个时刻更新。

解决方案

我发现了这个问题。 django admin使用视图范围的数据库事务。我需要手动提交事务,然后通知外部系统


I have a snippet of code like this in a Django application

def update_account(user_account,add_widget_count):
    user_account.add_widgets(add_widget_count)
    user_account.save()

    notify_other_system_about_account_update(user_account)

When I run this as part of my application, everything works great. In particular, when my other system (external to django) get the notification, it checks the database, and the widget count is updated.

However, when I run the above code from the admin website, there is an issue. When my other system gets the notification, it does not see the updated value in the database. I confirm by placing a breakpoint and checking in the database and it does not get updated after the call to .save() - in the non-admin-site call the DB is updated when I check during this breakpoint. Only after I let the app run its course, does the DB get updated.

Is the django admin middleware doing some sort of delaying or deferring od DB writes?

Update

I even moved the call to notify_other_system_about_account_update(user_account) to a post_save signal handler on my UserAccount object. The signal fires, but when I get it. The database updates at some point after my signal handler returns. This behavior only happens if running from within the admin website.

解决方案

I found the issue. The django admin uses view-wide DB transactions. I need to manually commit the transaction before notifying the external system

这篇关于django db写入在管理站点中运行时不会立即发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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