在模型的save()方法中如何处理可能的竞争条件?
例如,以下示例实现具有相关项目的有序列表的模型.当创建新项目时,将使用当前列表大小作为其位置.
从我可以看出,如果多个项目同时创建,这可能会出错.
class OrderedList(models.Model):
# ....
@property
def item_count(self):
return self.item_set.count()
class Item(models.Model):
# ...
name = models.CharField(max_length=100)
parent = models.ForeignKey(OrderedList)
position = models.IntegerField()
class Meta:
unique_together = (('parent','position'), ('parent', 'name'))
def save(self, *args, **kwargs):
if not self.id:
# use item count as next position number
self.position = parent.item_count
super(Item, self).save(*args, **kwargs)
我遇到了@transactions.commit_on_success(),但这似乎只适用于视图.即使它适用于模型方法,我仍然不知道如何正确处理失败的事务.
我正在卷曲地处理它,但感觉更像是一个黑客而不是一个解决方案
def save(self, *args, **kwargs):
while not self.id:
try:
self.position = self.parent.item_count
super(Item, self).save(*args, **kwargs)
except IntegrityError:
# chill out, then try again
time.sleep(0.5)
有什么建议么?
更新:
上述解决方案的另一个问题是,如果IntegrityError是由名称冲突(或任何其他唯一的字段)导致的,while循环将永远不会结束.
为了纪录,这是我到目前为止,这似乎做了我所需要的:
def save(self, *args, **kwargs):
# for object update, do the usual save
if self.id:
super(Step, self).save(*args, **kwargs)
return
# for object creation, assign a unique position
while not self.id:
try:
self.position = self.parent.item_count
super(Step, self).save(*args, **kwargs)
except IntegrityError:
try:
rival = self.parent.item_set.get(position=self.position)
except ObjectDoesNotExist: # not a conflict on "position"
raise IntegrityError
else:
sleep(random.uniform(0.5, 1)) # chill out, then try again