Django 模型唯一 = True 不会抛出任何在原子事务中使用的错误



>场景: 我正在尝试创建/插入数据到 Django 模型(POSTGRES 数据库(员工和配置文件。 当我插入重复记录(即具有重复work_email和重复employee_id(时,我预计原子事务中会出现数据库错误。

但是,下面的代码不会引发任何错误,但是当我看到数据库表时,不会创建重复项。

删除数据库并创建新的数据库和新的迁移,以确保同步没有问题。但是,结果是相同的,没有错误。

任何帮助,不胜感激。谢谢

class Employee(models.Model):
"""
Employee table containing all the employee information.
"""
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
id = models.CharField(max_length=50, unique=True, blank=False, default=uuid.uuid4, editable=False, db_index=True)
employee_id = models.CharField(
max_length=100,
blank=False,
unique=True,
primary_key=True,
error_messages={'employee_id': "A user with employee id already exists."}
)
class Profile(AbstractUser):
"""
Enhancing user model with additional fields. This is in relation with a table ProfileExtras.
Extras can be utilised to add any fields to further enhance Profile with key value pair.
"""
email = None
date_of_birth = models.DateField(blank=False)
work_email = models.EmailField(
max_length=50,
blank=False,
unique=True,
db_index=True,
error_messages={'work_email': "A user with work email already exists."}
)

def create_employee(app_context, data_dict):
try:
with transaction.atomic():
employee_model = models.Employee()
profile_model = models.Profile()
# Data insertion logic
# e.g. setattr(employee_model, "first_name", "xxxxxx")
employee_model.profile = profile_model
profile_model.save()
employee_model.save()
except Exception as e:
log.error(e)
raise e

找到了解决方案。我正在用 Django 测试进行测试。发现每个测试之间没有保留数据,因此不会引发重复错误。

最新更新