如何消除 django 中的唯一约束失败?
How do I eliminate Unique Constraint failure in django?
基于,我想在这里得到一个澄清。我如何确保 editing/updating 教师详细信息不会创建具有相同详细信息的新用户???我认为当我尝试 update/edit 一位已经保存的老师时就是这种情况。请帮帮我。
老师模型。
class TeacherData(models.Model):
id = models.AutoField(primary_key=True)
teacher_user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,blank=True)
school = models.ForeignKey(School,on_delete=models.CASCADE)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
code = models.IntegerField(unique=True)
email = models.EmailField()
phone = models.IntegerField()
def save(self, *args, **kwargs):
self.user = User.objects.create_user(username=self.first_name,password=str(self.code),is_teacher = True,is_student = False,school_id=self.school.id)
self.user.save() # mandatory as create_user is not recognized as save operation
super().save(*args, **kwargs)
用户模型。
class User(AbstractUser):
school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True)
#role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False)
is_student = models.BooleanField(default=True)
is_teacher = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
回溯。
Traceback (most recent call last):
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\edit.py", line 194, in post
return super().post(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid
self.object = form.save()
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\forms\models.py", line 460, in save
self.instance.save()
File "D:\Python\Django\Links Online Exams\Links_Online_Results\teachers\models.py", line 16, in save
self.user = User.objects.create_user(username=self.first_name,password=str(self.code),is_teacher = True,is_student = False,school_id=self.school.id)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\models.py", line 146, in create_user
return self._create_user(username, email, password, **extra_fields)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\models.py", line 140, in _create_user
user.save(using=self._db)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 790, in save_base
updated = self._save_table(
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 933, in _do_insert
return manager._insert(
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username
[21/Apr/2021 09:49:37] "POST /teachers/update/1 HTTP/1.1" 500 205276
如评论中所述,您的方法存在很多问题,但为了回答您的问题,您可以简单地捕获并忽略异常:
from django.db.utils import IntegrityError
...
class TeacherData(models.Model):
...
def save(self, *args, **kwargs):
try:
self.teacher_user = User.objects.create(
username=self.first_name,
password=str(self.code),
is_teacher=True,
is_student=False,
school_id=self.school.id)
except IntegrityError:
# User already exists
pass
super().save(*args, **kwargs)
基于
class TeacherData(models.Model):
id = models.AutoField(primary_key=True)
teacher_user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,blank=True)
school = models.ForeignKey(School,on_delete=models.CASCADE)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
code = models.IntegerField(unique=True)
email = models.EmailField()
phone = models.IntegerField()
def save(self, *args, **kwargs):
self.user = User.objects.create_user(username=self.first_name,password=str(self.code),is_teacher = True,is_student = False,school_id=self.school.id)
self.user.save() # mandatory as create_user is not recognized as save operation
super().save(*args, **kwargs)
用户模型。
class User(AbstractUser):
school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True)
#role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False)
is_student = models.BooleanField(default=True)
is_teacher = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
回溯。
Traceback (most recent call last):
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\edit.py", line 194, in post
return super().post(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid
self.object = form.save()
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\forms\models.py", line 460, in save
self.instance.save()
File "D:\Python\Django\Links Online Exams\Links_Online_Results\teachers\models.py", line 16, in save
self.user = User.objects.create_user(username=self.first_name,password=str(self.code),is_teacher = True,is_student = False,school_id=self.school.id)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\models.py", line 146, in create_user
return self._create_user(username, email, password, **extra_fields)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\models.py", line 140, in _create_user
user.save(using=self._db)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 790, in save_base
updated = self._save_table(
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 933, in _do_insert
return manager._insert(
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username
[21/Apr/2021 09:49:37] "POST /teachers/update/1 HTTP/1.1" 500 205276
如评论中所述,您的方法存在很多问题,但为了回答您的问题,您可以简单地捕获并忽略异常:
from django.db.utils import IntegrityError
...
class TeacherData(models.Model):
...
def save(self, *args, **kwargs):
try:
self.teacher_user = User.objects.create(
username=self.first_name,
password=str(self.code),
is_teacher=True,
is_student=False,
school_id=self.school.id)
except IntegrityError:
# User already exists
pass
super().save(*args, **kwargs)