Search code examples
pythondjangodictionarydatabase-migration

Django creates migration files after each 'makemigrations' because of set?


I've noticed strange things in my Django project. Each time I run python manage.py makemigrations command new migration file for my app called notifications is created. I did zero changes to the model, but the new migration file is created. I can run makemigrations command N number of times and N number of migration files will be created.

The model looks as following:

from django.db import models
from django.db.models.fields import EmailField


class EmailLog(models.Model):
    email = models.EmailField(max_length=70, null=False)
    subject = models.CharField(max_length=255, null=False)
    html_body = models.TextField(null=False)
    sent_choices = {
        ('OK', 'Sent'),
        ('KO', 'Not sent'),
        ('KK', 'Unexpected problems')
    }
    status = models.CharField(max_length=2, choices=sent_choices,
                              null=False, default='KO')
    sent_log = models.TextField(null=True)
    sent_date = models.DateTimeField(auto_now_add=True, null=False)

Each migration just swaps the position of sent_choices field. that's all!

Is it because sent_choices has a random order? How do I avoid it?


Solution

  • You are right - it is because of the set, which is unordered.

    I would recommend using a tuple instead.

    sent_choices = (
        ('OK', 'Sent'),
        ('KO', 'Not sent'),
        ('KK', 'Unexpected problems')
    )
    

    A tuple is also used in the django docs.