django - Django model unique=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 测试进行测试。发现每次测试之间没有保留数据,因此没有出现重复错误。
推荐阅读
- tensorflow - 为什么我的 MNSIT 数字项目的每个预测都是错误的?
- c - 在没有 C/Linux 中的磁盘 I/O 的情况下在 linux 上的自己的进程上读取调试/静态符号?
- spring - 使用 Spring Security 对用户进行身份验证
- c# - 如何仅从 win 表单中的文本文件中提取数字?
- date - ssh连接的生命周期
- dns - 对网络解决方案的担忧 合并了不当的商业行为
- xpath - 使用 XPath 获取“位置:”背后的内容
- powershell - cmd.exe 抛出错误“& 在这个时候是意外的。”
- python-3.x - 如何在多处理中的两个单独脚本之间传输数据?
- java - 可调用布尔值的语法是什么