是的。这肯定会导致问题。你有一个竞争条件。如果您愿意,您可以以某种方式在关键部分上获取锁,这将阻止下一次调用进入一段代码,直到第一次调用命令完成。您可能能够为基础数据执行行锁或表锁。
假设您使用的是具有特定锁定语法(依赖于数据库)的 MySQL,并且您具有以下模型:
class Email(models.Model):
sent = models.BooleanField(default=False)
subj = models.CharField(max_length=140)
msg = models.TextField()
你可以像这样创建一个锁对象:
from django.db import connection
[...]
class EmailLocks(object):
def __init__(self):
self.c = connection.cursor()
def __enter__(self):
self.c.execute('''lock tables my_app_email write''')
def __exit__(self, *err):
self.c.execute('unlock tables')
然后锁定所有关键部分,例如:
with EmailLocks():
# read the email table and decide if you need to process it
for e in Email.objects.filter(sent=False):
# send the email
# mark the email as sent
e.sent = True
e.save()
锁定对象将在退出时自动解锁表。此外,如果您在代码中抛出异常,该表仍将被解锁。