gpt4 book ai didi

python - get_or_create 抛出完整性错误

转载 作者:IT老高 更新时间:2023-10-28 21:10:05 28 4
gpt4 key购买 nike

鉴于 object.get_or_create() 的全部意义在于获取对象(如果它已经存在),我不明白为什么它会抛出此代码的完整性错误:

class UserAdd(TemplateView):

def post(self, request, *args, **kwargs):
context = self.get_context_data(*args, **kwargs)
form = UserAddForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
myemail = form.cleaned_data['email']
mypass = form.cleaned_data['password']
if myemail and mypass:
myuser,created = User.objects.get_or_create(email=myemail, username=myemail, first_name=first_name, last_name=last_name)
if created:
myuser.set_password(mypass)
return HttpResponseRedirect('/')

这是错误:

django.db.utils.IntegrityError IntegrityError: (1062, "Duplicate entry 'user@domain.com' for key 'username_UNIQUE'")

有人知道怎么回事吗?

最佳答案

发送到 get_or_create 方法的参数需要完全匹配,否则 django 的 ORM 会尝试创建一个新对象,并且由于会违反主键/唯一列约束,因此您将获得错误。

试试这个:

if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
myemail = form.cleaned_data['email']
mypass = form.cleaned_data['password']
if myemail and mypass:
myuser,created = User.objects.get_or_create(email=myemail, defaults = {'username': myemail, 'first_name': first_name, 'last_name': last_name})
if created:
myuser.set_password(mypass)

return HttpResponseRedirect('/')

阅读更多关于 get_or_create here . defaults= 参数是您所需要的。

关于python - get_or_create 抛出完整性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362085/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com