Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - unique_together change - any danger in prod db?

Tags:

python

django

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?

like image 451
doniyor Avatar asked Apr 22 '15 13:04

doniyor


1 Answers

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="")
like image 194
Timmy O'Mahony Avatar answered Oct 07 '22 15:10

Timmy O'Mahony