The Python Oracle

Adding BooleanField to django model ,this field for existing items should be True, for new items it should be False

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Adding Booleanfield To Django Model ,This Field For Existing Items Should Be True, For New Items It
00:40 Answer 1 Score 7
01:26 Accepted Answer Score 5
02:22 Thank you

--

Full question
https://stackoverflow.com/questions/5510...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangomodels #djangoforms

#avk47



ANSWER 1

Score 7


Add the field with default=True, and run makemigrations to create a migration. Then switch the default to False and run makemigrations again.

Then run migrate to run both migrations. When the first migration runs, Django will add the column and set all existing entries to True. The second migration won't change the value for existing rows.

With this approach, I think you'll end up with a small window between running the migrations and restarting your webserver where creating a new row through the website would cause a 'not null constraint failed'. If this is unacceptable, then you can create the field with null=True, run the migrations, then remove null=True and run a final data migration to change any nulls to True or False as required.




ACCEPTED ANSWER

Score 5


Well, there are many options on how to handle this situation. One would be to first simply add the field without a default value and ask Django to create the appropriate migration. So your model should look like:

class FlagSetting(models.Model):
    name = models.CharField(max_length=10)
    flag = models.BooleanField()

When you run the command manage.py makemigrations Django will ask what to do, you can choose to provide a 'one-off default value'. This value will be used to populate existing instances. By doing this the migration code generated by Django will set your provided one-off default value to all previously existing instances.

Afterwards you should change your model again in order to set the desired default value for your field so your model looks like:

class FlagSetting(models.Model):
    name = models.CharField(max_length=10)
    flag = models.BooleanField(default=False)

And then you have to run manage.py makemigrations again. This time a new migration will be created to set the default value to False. Then every newly created instance is going to have flag=False by default.