可能的解决方案:
假设我有一个客户模型。
Customer.objects.order_by('primay_key_id ').last().primay_key_id + 2)
primay_key_id = models.IntegerField(default=(Customer.objects.order_by('primay_key_id ').last().primay_key_id + 2),primary_key=True)
或
from django.db import transaction
#Uncomment Lines for Django version less than 2.0
def save(self):
"Get last value of Code and Number from database, and increment before save"
#with transaction.atomic():
#top = Customer.objects.select_for_update(nowait=True).order_by('-customer_customerid')[0] #Ensures Lock on Database
top = Customer.objects.order_by('-id')[0]
self.id = top.id + 1
super(Customer, self).save()
上述代码对于 Django 2.0 不会有并发问题:
从 Django 2.0 开始,默认情况下相关行被锁定(不确定之前的行为是什么),并且可以使用 of 参数以与 select_related 相同的样式指定要锁定的行!
对于较低版本,您需要是原子的!
或
from django.db import transaction
def increment():
with transaction.atomic():
ids = Customer.objects.all()
length = len(ids)-1
if(length<=0): #Changed to Handle empty Entries
return 1
else:
id = ids[length].customer_customerid
return id+2
或
from django.db import transaction
def increment():
with transaction.atomic():
return Customer.objects.select_for_update(nowait=True).order_by('-customer_customerid')[0] #Ensures Atomic Approach!
并将模型中的主键设置为整数字段,并在每个新条目上设置primary_key_field=increment() Like
然后在你的 Models.py 中
将 Primary_Key 设置为:
import increment()
primay_key_id = models.IntegerField(default=increment(),primary_key=True)