简体   繁体   English

Django Celery:芹菜的任务中不存在模型对象(ATOMIC_REQUESTS=False)

[英]Django Celery: Model object does not exists within the celery's task (ATOMIC_REQUESTS=False)

I am getting MyModel matching query does not exist.我得到MyModel matching query does not exist. error while fetch the object which I am creating before entering the celery task.在进入 celery 任务之前获取我正在创建的对象时出错。 I am calling the task from within my APIView .我正在从我的APIView调用任务。

my_model_obj = MyModel(x=1, y=2)
my_model_obj.save()
my_celery_task.delay(my_model_obj.id)

within my task function, I am doing:在我的任务功能中,我正在做:

@task()
def my_celery_task(my_model_id):
    MyModel.objects.get(id=my_model_id)

I do not have ATOMIC_REQUESTS param in my Django's DATABASE configuration.我的 Django 的DATABASE配置中没有ATOMIC_REQUESTS参数。 So, by default it should be False.因此,默认情况下它应该是 False。

I believe it is because the Django is releasing control from the model object even before the data is been actually saved to the DB.我相信这是因为 Django 甚至在数据实际保存到数据库之前就从模型对象中释放了控制权。 This is an intermittent issue which happens sometime and sometime it works fine.这是一个间歇性问题,有时会发生,有时它工作正常。

Earlier I had the similar issue in which I was updating the values of model object but the updated values were not reflecting within the celery's task.早些时候我遇到了类似的问题,我正在更新模型对象的值,但更新的值没有反映在芹菜的任务中。 In order to make that run, I have added 10 secs of delay.为了运行,我增加了 10 秒的延迟。 But this time I am looking for some permanent solution.但这次我正在寻找一些永久的解决方案。 Is there some way to fix this?有没有办法解决这个问题? I haven't got any configuration param in neither Django's or Celery's configuration to deal with this kind of behavior.我在 Django 或 Celery 的配置中都没有任何配置参数来处理这种行为。

The issue was because I was using TransactionMiddleware , and it does similar thing as @transaction.commit_on_success decorator.问题是因为我使用的是TransactionMiddleware ,它与@transaction.commit_on_success装饰器做类似的事情。 If you want to keep using TransactionMiddleware , you should look into using @transaction.autocommit decorator in your views with celery tasks, or @transaction.commit_manually如果你想继续使用TransactionMiddleware ,你应该考虑在你的视图中使用@transaction.autocommit装饰器和 celery 任务,或者@transaction.commit_manually

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM