1

I would like to know if there is any conflict using the constraint unique_together as well as the parameter unique=true in one of the fields that belong to the array of the unique_together.

I can´t remove the parameter unique=true of my field because it´s used as a the foreign key in another model.

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']

As you can see the goal is to make the combination of the fields fiscal_number and email unique.

masseyb
  • 3,745
  • 1
  • 17
  • 29

1 Answers1

0

Basically, I would like to know if there is any conflict using the constrain unique_together as well as the parameter unique=true in one of the fields that belong to the array of the unique_together.

It makes no sense. Indeed, by setting unique=True it means that there can't be two users with the same fiscal_number, unless if these two users are the same user.

The unique_together = ['fiscal_year', 'email'] means that the combination of a fiscal_year and an email has to be unique. That means that there can't be two users where both the fiscal_year and the email are the same (unless these two users are the same user). But since we already made fiscal_year as a field unique, we already know that this can not happen.

You can mark the email field as unique=True as well. This is not equivalent to unique_together = ['fiscal_number', 'email']. With unique_together, the combination of the two columns should be unique, whereas setting unique=True on multiple fields, means that all Users have a different fiscal_year, and a different email, etc.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • yeah you are right. But if i only set the **fiscal_number** with the parameter **unique=true** could happen that many **fiscal_number** have the same email and that´s what I need to avoid, because I have to make that every **fiscal_number** be unique and also has a unique **email**, that´s why I thought to use the **unique_together** constraint. Or do you thing that there is another way to solve it ? – user15854983 Dec 03 '21 at 22:36
  • @user15854983: you can make `email` unique as well. But the `unique_together` here is *implied* by the fact that the `fiscal_number` is already unique. – Willem Van Onsem Dec 03 '21 at 22:39
  • oh yes, I also thought that but I didn´t know that was possible, to have two fields unique. I´m going to try bro, thank you – user15854983 Dec 03 '21 at 22:44