鉴于 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'")
有谁知道发生了什么?