1

我想知道使用约束unique_together以及unique=true属于unique_together.

我无法删除unique=true我的字段的参数,因为它在另一个模型中用作外键。

class User(AbstractUser):
  # User information
  fiscal_number = models.CharField(max_length=30,unique=True)
  phone = models.CharField(max_length=15, null=True)
  email = models.EmailField(max_length=254, verbose_name='email address')

  class Meta:
    unique_together = ['fiscal_number', 'email']

如您所见,目标是使字段的组合fiscal_number独一无二email

4

1 回答 1

0

基本上,我想知道使用约束 unique_together 以及unique=true属于unique_together.

这没有任何意义。实际上,通过设置unique=True它意味着不能有两个用户具有相同的fiscal_number,除非这两个用户是同一个用户。

unique_together = ['fiscal_year', 'email']意味着a和 an的组合必须是唯一的。这意味着不能有两个用户两者都相同(除非这两个用户是同一个用户)。但是由于我们已经将其作为一个独特的领域,我们已经知道这不可能发生。fiscal_yearemailfiscal_yearemailfiscal_year

您也可以标记该email字段unique=True。这等于unique_together = ['fiscal_number', 'email']. 使用unique_together,两列的组合应该是唯一的,而unique=True在多个字段上设置,意味着所有User的 s 都有不同的fiscal_year,和不同的email,等等。

于 2021-12-03T22:26:18.173 回答