正如他们在文档中告诉我们的那样,我试图使用on_commit方法,但我仍然在通过delay((启动的任务中得到ModelDoesNotExistError。
views.py:
class SomeViewset(viewsets.ModelViewset):
...
@action(detail=True, methods=['post'])
def some_action(self, request, *args, **kwargs):
m = MyModel()
with transaction.atomic():
m.save()
transaction.on_commit(lambda:
my_fav_task.delay(m.id, param2, param3))
return Response({"success": True, "operation_id": m.id}, status=status.HTTP_200_OK)
tasks.py:
@shared_task
def my_fav_task(operation_id, **params):
print(operation_id) # We get new id
print(MyModel.objects.all()) # No newly created object here
operation = MyModel.objects.get(id=operation_id) # Error here
我的问题是在芹菜和django之间没有明显使用不同的数据库。执行这个过程的docker容器似乎为自己创建了本地数据库,因为我不愿意在没有特殊共享的情况下使用标准的db.sqlite3
from django.db import transactions
@transaction.atomic
def view(request):
m = MyModel()
m.save()
# Execute celery task only after database changes (m.save())
transaction.on_commit(lambda: my_fav_task.delay(m.id, param2, param3))
return Response({"success": True, "operation_id": m.id}, status=status.HTTP_200_OK)