使用 celery 更新 Django 模型字段时避免递归 save() [英] Avoid recursive save() when using celery to update Django model fields

查看:28
本文介绍了使用 celery 更新 Django 模型字段时避免递归 save()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写模型的 save() 方法以使用 Celery 调用异步任务.该任务还保存了模型,因此我最终遇到了 Celery 任务被重复调用的递归情况.代码如下:

I'm overriding a model's save() method to call an asynchronous task with Celery. That task also saves the model, and so I end up with a recursive situation where the Celery task gets called repeatedly. Here's the code:

模型的保存方法:

def save(self, *args, **kwargs):
    super(Route, self).save(*args, **kwargs)
    from .tasks import get_elevation_data
    get_elevation_data.delay(self)

get_elevation_data 任务:

from celery.decorators import task

@task()
def get_elevation_data(route):
    ...
    route.elevation_data = results
    route.save()

如何避免这种递归?

推荐答案

添加一个关键字参数告诉 save 不要递归:

Add a keyword argument that tells save not to recurse:

 def save(self, elevation_data=True, *args, **kwargs):
   super(Route, self).save(*args, **kwargs)
   if elevation_data:
     from .tasks import get_elevation_data
     get_elevation_data.delay(self)

然后:

 from celery.decorators import task

 @task()
 def get_elevation_data(route):
     ...
     route.elevation_data = results
     route.save(elevation_data=False)

这篇关于使用 celery 更新 Django 模型字段时避免递归 save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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