[英]IntegrityError: UNIQUE constraint failed, how to catch and respond
[英]IntegrityError :UNIQUE constraint failed: theatre_audience.ticketId
我正在尝试创建一个 Django 应用程序来为剧院中的观众分配座位(用于现场表演)。 每当我尝试添加新受众时,我都无法添加多个受众。 它给出了 UNIQUE 约束失败错误。 在这里,在我的代码中,我正在尝试使用 UUID 字段创建一个 ticketId。 但是,它不会为不止一个观众保存。
我的 model
from django.db import models
import uuid
# Create your models here.
class Audience(models.Model):
name = models.CharField(max_length=200, null=True)
ticketId = models.UUIDField(
primary_key = True,
default = uuid.uuid4(),
editable = False
)
seatNo = models.IntegerField(default=0)
我的应用程序
def occupy(request, pname):
arr = [i for i in range(1,Total_seats+1)]
inst = Audience()
inst.name = pname
num = Audience.objects.values_list('seatNo')
print(num)
for i in num:
v = i[0]
arr.remove(i[0])
print(arr)
if(len(arr)<1):
msg="All seats are occupied"
context={"msg":msg}
return render(request,"theatre/ERROR.html",context)
else:
seatn = random.choice(arr)
inst.seatNo = seatn
inst.save()
temp = Audience.objects.get(seatNo = seatn)
context = {"temp":temp}
return render(request, "theatre/show.html", context)
我在以下行中收到错误上述异常(UNIQUE 约束失败:theatre_audience.ticketId)是以下异常的直接原因:
inst.save()
default = uuid.uuid4(),
仅在处理 class 定义时执行uuid4()
一次,因此对于不为ticketId
提供显式值的所有新Audience
记录, default
将是相同的值。 这将违反主键字段的唯一约束。
您可以将可调用对象作为默认值传递,因此使 function 本身(不调用它):
ticketId = models.UUIDField(
primary_key = True,
default = uuid.uuid4, # do not call, just pass the callable
editable = False
)
将解决问题。 或者,您可以在每次创建Audience
记录时手动生成新的 UUID:
inst = Audience(ticketId=uuid.uuid64())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.