首页 > 解决方案 > 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

标签: djangopostgresqldjango-modelsdjango-3.0

解决方案


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


推荐阅读