|
UnderstandingMigrations
How migrations work and how they are managed
Featured The migrations directoryMigrations live in the directory specified by your DMIGRATIONS_DIR setting. A migration is a .py file whose name consists of a number, an underscore and a textual description. For example, 03_add_table_foo.py. The number is significant because it specifies the default order in which migrations will be applied, and also provides a shorthand way to refer to a specific migration when running the dmigrate command. Leading 0s are ignored, which allows migrations to be sorted correctly by ls and filesystem browsers. The numbering sequence does not need to be continuous - you can leave gaps in between migration numbers if you like. This is important when using migrations in a branched development environment. At Global Radio we use a wiki page to "reserve" migration numbers every time a migration is created - that way branches can build different migrations which will still apply in the correct order when the branches are merged (provided those migrations don't conflict with each other in some way). Migration order is used by dmigrate up, dmigrate down, dmigrate all and also by the dmigrate to, dmigrate upto and dmigrate downto commands. The anatomy of a migrationA migration's filename is used to indicate the order in which it should be applied. The file itself is a Python module containing Python code. The only requirement is that the file contains a module level symbol called "migration" which is an instance of a BaseMigration subclass. This object should have an up() method and a down() method. The former is called when the migration is applied; the latter when the migration is unapplied. The down method should perform the opposite action to the up method. For example, if the up method added a database table the down method should remove it again. The migrations generated by the dmigration command all have their up and down methods automatically created to be opposites of each other. |