Django Migrations Add Field with Default as Function of Model

前端 未结 3 560
萌比男神i
萌比男神i 2020-12-02 09:31

I added a new, non-nullable field to my Django model and am trying to use migrations to deploy that change. How would I set default value to use for existing models to be so

3条回答
  •  爱一瞬间的悲伤
    2020-12-02 10:15

    You need to do it in two migrations. First of all, add your field, but make nullable. Create a migration file as usual. After that set your field to not-nullable and run makemigrations again, but don't lauch migrate yet. Open the second migration and define a function at the top:

    def set_field_values(apps, schema_editor):
        # use apps.get_model("app_name", "model_name") and set the defualt values
    

    then, in your migration file there is a list of operations. Before the alter field operation add

    RunPython(set_field_values)
    

    and it should do it

提交回复
热议问题