Add non-null and unique field with already populated model

后端 未结 2 721
迷失自我
迷失自我 2021-02-07 02:27

I have one model in my app running in a server with a few entries. I need to add a SlugField, unique and not-null for this model. The SlugField will be

相关标签:
2条回答
  • 2021-02-07 02:51

    You do your model changes (add field, change, etc), then you call manage.py makemigrations, then apply the migrations with manage.py migrate

    You can add the field with null=True, then you e.g. make a script to populate it one time

    Otherwise, if you need to populate the field within the migration you can write a custom one, see https://docs.djangoproject.com/en/1.7/ref/migration-operations/#writing-your-own

    0 讨论(0)
  • 2021-02-07 02:57

    Unfortunatelly, I found no answer but I could create one solution:

    • First I have created a migration that allows the slug field to be nullable;
    • Then I have created another migration that populates the slug column with proper values to every row in the model;
    • Then another migration which adds the not-null constraint in the column.
    0 讨论(0)
提交回复
热议问题