0

I have a class that inherits from models.IntegerChoices and defines certain constants I use in my model. I want to make the "labels" of my integer choices a variable in the settings.py:

class Status(models.IntegerChoices):
    ONE = 0, settings.ONE_LABEL
    TWO = 1, settings.TWO_LABEL

When playing around with this I found that whenever I change ONE_LABEL or TWO_LABEL in my settings, Django would like to create a new migration similar to

migrations.AlterField(
    model_name='mymodel',
    name='status',
    field=models.IntegerField(choices=[(0, 'New one label'), (1, 'New two label')], default=0),
)

My goal is to deploy multiple (very similar) servers where only UI elements (that display the names of status) change according to the values in my settings. I guess it is not wise to allow changes in my settings to trigger any changes in the database, as that would make updating later versions of my project much harder. Is it safe to ignore the possible migration? I thought the way above is the easiest as I have multiple model forms and other components that use the label of my status class. This would allow a single change in my settings to be transferred throughout my project. I can't see why changing the label would require a DB migration as long as I don't change the values. I wonder if there is any better way to achieve the same goal.

michip96
  • 363
  • 3
  • 12
  • why do you need integerchoices, which will save the value to the databases? Can you just use environment variable? For example check how django is already using DEBUG variable, you can add a new variable and change the settings mode accordingly – andylee May 11 '23 at 02:59
  • I liked that IntegerChoices seem to be very well integrated into components like forms etc. – michip96 May 11 '23 at 08:22

1 Answers1

1

Django create new migrations when it detects changes between your current models in your code and your migrations.

To avoid django from creating a new migration when you change your settings, you could update your migration file directly, so that no changes would be detected :

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        # your dependencies
    ]

    operations = [
        migrations.AlterField(
            model_name='mymodel',
            name='status',
            field=models.IntegerField(choices=[(0, settings.ONE_LABEL), (1, settings.TWO_LABEL)], default=0),
)
    ]

Charlesthk
  • 9,394
  • 5
  • 43
  • 45
  • That is an excellent suggestion. What will happen (in the DB) with the values of `settings.ONE_LABEL` and `settings.TWO_LABEL`? Why are they needed at all? – michip96 May 11 '23 at 18:02
  • 1
    This won't affect your database. When you change your choices, django creates a new migrations to keep a full accurate history of your model changes. See a full explanation here : https://stackoverflow.com/a/26186194/1405425 – Charlesthk May 11 '23 at 18:21