在使用芹菜更新Django模型字段时,避免使用递归的save()方法 [英] Avoid recursive save() when using celery to update Django model fields
本文介绍了在使用芹菜更新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()
如何避免这种递归?
推荐答案
添加一个关键字参数,指示保存不要递归:
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)
这篇关于在使用芹菜更新Django模型字段时,避免使用递归的save()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文