0
假設具有兩個字段的django模型: - 創建 - 修改 每個字段都是整數,唯一併且值不斷增加。一個對象在第一次保存時應該具有相同的創建和修改值,並且修改後的字段應該在每次保存時增加到大於自身的下一個空閒值。避免custon Django字段中的完整性錯誤
我創建爲宗旨以下字段:
class CreatedVerisonField(models.BigIntegerField):
update_on_each_save = False
def __init__(self, *args, **kwargs):
kwargs.setdefault('editable', False)
kwargs.setdefault('blank', True)
kwargs.setdefault('unique', True)
models.BigIntegerField.__init__(self, *args, **kwargs)
def pre_save(self, model, add):
if add or self.update_on_each_save:
value = self.get_next_value(model)
setattr(model, self.attname, value)
return value
else:
return super(CreatedVerisonField, self).pre_save(model, add)
def get_next_value(self, model):
objs = model.__class__.objects.all()
fields = self._get_fields(model)
if objs:
# new version is max of all version fields + 1
value = max(objs.aggregate(*map(lambda x: Max(x), fields)).values()) + 1
else:
value = 1
return value
def _get_fields(self, model):
fields = []
for f in model._meta.fields:
if isinstance(f, CreatedVerisonField):
fields.append(f.db_column if f.db_column else f.name)
return fields
class ModifiedVersionField(CreatedVerisonField):
def __init__(self, *args, **kwargs):
self.update_on_each_save = True
CreatedVerisonField.__init__(self, args, kwargs)
使用這些領域的一個簡單的測試類:
class TestModel(models.Model):
created = CreatedVerisonField()
modified = ModifiedVersionField()
當創建和保存從多個線程「TestModel」的對象,我由於唯一約束而導致IntegretyError被違反。尋找pre_save代碼,很顯然這個比賽存在。我該如何解決?