[英]Django - Delay in creating database entry
I have a Django app where I create a db entry in the view. 我有一个Django应用,可在视图中创建数据库条目。 I then want to perform background processing on the new entry.
然后,我想对新条目执行后台处理。 Instead of sending the created object to the task, I send the object's id then the background task can fetch the db object as explained here .
我将对象的ID发送给任务,而不是将创建的对象发送给任务,然后后台任务可以按此说明获取db对象。 Below is my code:
下面是我的代码:
# In tasks.py
@shared_task
def my_task(model_id):
my_model = MyModel.objects.get(pk=model_id)
# Do stuff with my_model
# In views.py:
def some_view(request):
if request.method == 'POST' and request.is_ajax():
instance = MyModel.objects.create(**kwargs)
tasks.my_task.delay(instance.id)
....
However, when I try to get the object in the background task, I get matching query does not exist error. 但是,当我尝试在后台任务中获取对象时,我得到匹配的查询不存在错误。 If I add
sleep(1)
before getting the object, it works as excepted. 如果我在获取对象之前添加了
sleep(1)
,则它的作用与众不同。 I do not understand why I'm getting this error, since the object should be in the DB? 我不明白为什么出现此错误,因为对象应该在数据库中? Does anybody know how to solve this?
有人知道如何解决这个问题吗? I don't really want to add a sleep command everywhere.
我真的不想到处添加一个sleep命令。
I'm using Postgres as my DB. 我使用Postgres作为我的数据库。
Try this 尝试这个
from django.db import transaction
with transaction.atomic():
instance = MyModel.objects.create(**kwargs)
tasks.my_task.delay(instance.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.