5

I have a model:

class MyModel(models.Model):
   name = models.CharField(max_length=10)
   nickname = models.CharField(max_length=10)
   title = models.CharField(max_length=10)
   score = models.CharField(max_length=10)

   class Meta: 
      unique_together = ['name', 'nickname']

What is the impact of changing unique_together to

unique_together = ['name', 'title']

Should I be careful before deploying this update? There are more than 150.000 users online at the same time, what could happen in the worst case?

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • See this related [question](http://stackoverflow.com/q/8253550/1761793) – Ajoy Apr 22 '15 at 14:00
  • @Ajoy yes but in my case, I am just switched the existing unique keys. but thanks very imformative link – doniyor Apr 22 '15 at 14:07
  • I think it will have the same effect as adding a new constraint. You could try it on some test data first. – Ajoy Apr 22 '15 at 14:10

1 Answers1

6

Yes, I would be careful deploying this change as it affects the database. From the documentation:

This is a tuple of tuples that must be unique when considered together. It’s used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).

so you will need to migrate your database to change the UNIQUE constraint.

python manage.py makemigrations myapp
python manage.py migrate myapp

You will also need to check that there aren't any existing instances of your model that are sharing that pairing of unique constraints. You could check with something like:

MyModel.objects.filter(name__exact=models.F(title)).exists()

and amend or delete them.

You will also need to ensure that every model instance actually has a title and isn't an empty string (even though this probably shouldn't have happened).

MyModel.objects.filter(title__exact="")
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • 3
    Only other "danger" I would add is the possibility that (depending on the size of the table) the migration could take a very long time to create the new index. – Matt Briançon Apr 22 '15 at 15:45
  • @MattBriançon good point, i updated my question regarding number of users online, was my typo – doniyor Apr 22 '15 at 15:49