Django migration strategy for renaming a model and relationship fields

后端 未结 12 1604
一个人的身影
一个人的身影 2020-11-28 00:54

I\'m planning to rename several models in an existing Django project where there are many other models that have foreign key relationships to the models I would like to rena

12条回答
  •  攒了一身酷
    2020-11-28 01:54

    Unfortunately, I found problems (each django 1.x) with rename migration which leave old table names in the database.

    Django doesn't even try anything on the old table, just rename his own model. The same problem with foreign keys, and indices in general - changes there are not tracked properly by Django.

    The simplest solution (workaround):

    class Foo(models.Model):
         name = models.CharField(unique=True, max_length=32)
         ...
    Bar = Foo  # and use Bar only
    

    The real solution (an easy way to switch all indices, constraints, triggers, names, etc in 2 commits, but rather for smaller tables):

    commit A:

    1. create the same model as the old one
    # deprecated - TODO: TO BE REMOVED
    class Foo(model.Model):
        ...
    
    class Bar(model.Model):
        ...
    
    1. switch code to work with new model Bar only. (including all relations on the schema)

    In migration prepare RunPython, which copy data from Foo to Bar (including id of Foo)

    1. optional optimization (if needed for greater tables)

    commit B: (no rush, do it when an entire team is migrated)

    1. safe drop of the old model Foo

    further cleanup:

    • squash on migrations

    bug in Django:

    • https://code.djangoproject.com/ticket/23577

提交回复
热议问题