Django makemigrations keeps making the same alteration

Question:

I have a django project built with Django 1.10.7 and mysql 14.14 Distrib 5.5.54

If I do:

$ python manage.py makemigrations my_app

I get:

Migrations for ‘my_app’:
my_app/migrations/0023_auto_20180301_1419.py:
– Alter field reference on league

Then:

$ python manage.py migrate

Operations to perform:
Apply all migrations: admin, auth, contenttypes, my_app, sessions
Running migrations:
Applying my_app.0023_auto_20180301_1419… OK

Then, just after, I do:

$ python manage.py makemigrations my_app

I get:

Migrations for ‘my_app’:
my_app/migrations/0024_auto_20180301_1421.py:
– Alter field reference on league

As you can see it is the same alteration as before. It seems that django does not make the migrations well, or does but does not detect anything.

In models.py, the class is as follows:

class League(models.Model):
    name = models.CharField(max_length=50)
    id_creator = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    id_tour = models.ForeignKey('Tour', on_delete=models.CASCADE)
    step = models.IntegerField(default=0)
    creation_date = models.DateTimeField(default=timezone.now)
    reference = models.CharField(max_length=20, default=id_generator())

    def __str__(self):
        return self.name

What have I done wrong ?

Asked By: vvvvv

||

Answers:

Provide the id_generator function as the default value instead of the returned value of it. The function will be called every time when the new object is created.

reference = models.CharField(max_length=20, default=id_generator)

Django makemigrations keeps making the same alteration

I hit this due to my own silliness and hopefully this will save someone a little time. I ultimately did not have the same problem as the OP, but did have the same symptom.

I already had a list of states/country pairs, so I found it convenient to refer to that when creating a new model class. I used a set generator to pull out the countries while eliminating duplicates:

list_country = models.CharField("List Country", max_length=256, null=True, blank=True,  
    choices={(y, y) for (x, y) in TAXABLE_STATES})

Django kept wanting to alter field on list_country, over and over.

Then I noticed in each migration it was just re-ordering the countries. Of course, order is arbitrary in sets. I applied sorted() and my problem was solved.

list_country = models.CharField("List Country", max_length=256, null=True, blank=True,  
    choices=sorted({(y, y) for (x, y) in TAXABLE_STATES}))
Answered By: Benjamin Johnson
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.