migrations.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. ==========
  2. Migrations
  3. ==========
  4. .. module:: django.db.migrations
  5. :synopsis: Schema migration support for Django models
  6. .. versionadded:: 1.7
  7. Migrations are Django's way of propagating changes you make to your models
  8. (adding a field, deleting a model, etc.) into your database schema. They're
  9. designed to be mostly automatic, but you'll need to know when to make
  10. migrations, when to run them, and the common problems you might run into.
  11. A Brief History
  12. ---------------
  13. Prior to version 1.7, Django only supported adding new models to the
  14. database; it was not possible to alter or remove existing models via the
  15. ``syncdb`` command (the predecessor to :djadmin:`migrate`).
  16. Third-party tools, most notably `South <http://south.aeracode.org>`_,
  17. provided support for these additional types of change, but it was considered
  18. important enough that support was brought into core Django.
  19. The Commands
  20. ------------
  21. There are several commands which you will use to interact with migrations
  22. and Django's handling of database schema:
  23. * :djadmin:`migrate`, which is responsible for applying migrations, as well as
  24. unapplying and listing their status.
  25. * :djadmin:`makemigrations`, which is responsible for creating new migrations
  26. based on the changes you have made to your models.
  27. * :djadmin:`sqlmigrate`, which displays the SQL statements for a migration.
  28. It's worth noting that migrations are created and run on a per-app basis.
  29. In particular, it's possible to have apps that *do not use migrations* (these
  30. are referred to as "unmigrated" apps) - these apps will instead mimic the
  31. legacy behavior of just adding new models.
  32. You should think of migrations as a version control system for your database
  33. schema. ``makemigrations`` is responsible for packaging up your model changes
  34. into individual migration files - analogous to commits - and ``migrate`` is
  35. responsible for applying those to your database.
  36. The migration files for each app live in a "migrations" directory inside
  37. of that app, and are designed to be committed to, and distributed as part
  38. of, its codebase. You should be making them once on your development machine
  39. and then running the same migrations on your colleagues' machines, your
  40. staging machines, and eventually your production machines.
  41. .. note::
  42. It is possible to override the name of the package which contains the
  43. migrations on a per-app basis by modifying the :setting:`MIGRATION_MODULES`
  44. setting.
  45. Migrations will run the same way on the same dataset and produce consistent
  46. results, meaning that what you see in development and staging is, under the
  47. same circumstances, exactly what will happen in production.
  48. Django will make migrations for any change to your models or fields - even
  49. options that don't affect the database - as the only way it can reconstruct
  50. a field correctly is to have all the changes in the history, and you might
  51. need those options in some data migrations later on (for example, if you've
  52. set custom validators).
  53. Backend Support
  54. ---------------
  55. Migrations are supported on all backends that Django ships with, as well
  56. as any third-party backends if they have programmed in support for schema
  57. alteration (done via the :doc:`SchemaEditor </ref/schema-editor>` class).
  58. However, some databases are more capable than others when it comes to
  59. schema migrations; some of the caveats are covered below.
  60. PostgreSQL
  61. ~~~~~~~~~~
  62. PostgreSQL is the most capable of all the databases here in terms of schema
  63. support; the only caveat is that adding columns with default values will
  64. cause a full rewrite of the table, for a time proportional to its size.
  65. For this reason, it's recommended you always create new columns with
  66. ``null=True``, as this way they will be added immediately.
  67. MySQL
  68. ~~~~~
  69. MySQL lacks support for transactions around schema alteration operations,
  70. meaning that if a migration fails to apply you will have to manually unpick
  71. the changes in order to try again (it's impossible to roll back to an
  72. earlier point).
  73. In addition, MySQL will fully rewrite tables for almost every schema operation
  74. and generally takes a time proportional to the number of rows in the table to
  75. add or remove columns. On slower hardware this can be worse than a minute per
  76. million rows - adding a few columns to a table with just a few million rows
  77. could lock your site up for over ten minutes.
  78. Finally, MySQL has reasonably small limits on name lengths for columns, tables
  79. and indexes, as well as a limit on the combined size of all columns an index
  80. covers. This means that indexes that are possible on other backends will
  81. fail to be created under MySQL.
  82. SQLite
  83. ~~~~~~
  84. SQLite has very little built-in schema alteration support, and so Django
  85. attempts to emulate it by:
  86. * Creating a new table with the new schema
  87. * Copying the data across
  88. * Dropping the old table
  89. * Renaming the new table to match the original name
  90. This process generally works well, but it can be slow and occasionally
  91. buggy. It is not recommended that you run and migrate SQLite in a
  92. production environment unless you are very aware of the risks and
  93. its limitations; the support Django ships with is designed to allow
  94. developers to use SQLite on their local machines to develop less complex
  95. Django projects without the need for a full database.
  96. Workflow
  97. --------
  98. Working with migrations is simple. Make changes to your models - say, add
  99. a field and remove a model - and then run :djadmin:`makemigrations`::
  100. $ python manage.py makemigrations
  101. Migrations for 'books':
  102. 0003_auto.py:
  103. - Alter field author on book
  104. Your models will be scanned and compared to the versions currently
  105. contained in your migration files, and then a new set of migrations
  106. will be written out. Make sure to read the output to see what
  107. ``makemigrations`` thinks you have changed - it's not perfect, and for
  108. complex changes it might not be detecting what you expect.
  109. Once you have your new migration files, you should apply them to your
  110. database to make sure they work as expected::
  111. $ python manage.py migrate
  112. Operations to perform:
  113. Synchronize unmigrated apps: sessions, admin, messages, auth, staticfiles, contenttypes
  114. Apply all migrations: books
  115. Synchronizing apps without migrations:
  116. Creating tables...
  117. Installing custom SQL...
  118. Installing indexes...
  119. Installed 0 object(s) from 0 fixture(s)
  120. Running migrations:
  121. Applying books.0003_auto... OK
  122. The command runs in two stages; first, it synchronizes unmigrated apps
  123. (performing the same functionality that ``syncdb`` used to provide), and
  124. then it runs any migrations that have not yet been applied.
  125. Once the migration is applied, commit the migration and the models change
  126. to your version control system as a single commit - that way, when other
  127. developers (or your production servers) check out the code, they'll
  128. get both the changes to your models and the accompanying migration at the
  129. same time.
  130. Version control
  131. ~~~~~~~~~~~~~~~
  132. Because migrations are stored in version control, you'll occasionally
  133. come across situations where you and another developer have both committed
  134. a migration to the same app at the same time, resulting in two migrations
  135. with the same number.
  136. Don't worry - the numbers are just there for developers' reference, Django
  137. just cares that each migration has a different name. Migrations specify which
  138. other migrations they depend on - including earlier migrations in the same
  139. app - in the file, so it's possible to detect when there's two new migrations
  140. for the same app that aren't ordered.
  141. When this happens, Django will prompt you and give you some options. If it
  142. thinks it's safe enough, it will offer to automatically linearize the two
  143. migrations for you. If not, you'll have to go in and modify the migrations
  144. yourself - don't worry, this isn't difficult, and is explained more in
  145. :ref:`migration-files` below.
  146. Dependencies
  147. ------------
  148. While migrations are per-app, the tables and relationships implied by
  149. your models are too complex to be created for just one app at a time. When
  150. you make a migration that requires something else to run - for example,
  151. you add a ``ForeignKey`` in your ``books`` app to your ``authors`` app - the
  152. resulting migration will contain a dependency on a migration in ``authors``.
  153. This means that when you run the migrations, the ``authors`` migration runs
  154. first and creates the table the ``ForeignKey`` references, and then the migration
  155. that makes the ``ForeignKey`` column runs afterwards and creates the constraint.
  156. If this didn't happen, the migration would try to create the ``ForeignKey``
  157. column without the table it's referencing existing and your database would
  158. throw an error.
  159. This dependency behavior affects most migration operations where you
  160. restrict to a single app. Restricting to a single app (either in
  161. ``makemigrations`` or ``migrate``) is a best-efforts promise, and not
  162. a guarantee; any other apps that need to be used to get dependencies correct
  163. will be.
  164. .. _unmigrated-dependencies:
  165. Be aware, however, that unmigrated apps cannot depend on migrated apps, by the
  166. very nature of not having migrations. This means that it is not generally
  167. possible to have an unmigrated app have a ForeignKey or ManyToManyField to
  168. a migrated app; some cases may work, but it will eventually fail.
  169. This is particularly apparent if you use swappable models (e.g.
  170. ``AUTH_USER_MODEL``), as every app that uses swappable models will need
  171. to have migrations if you're unlucky. As time goes on, more and more
  172. third-party apps will get migrations, but in the meantime you can either
  173. give them migrations yourself (using :setting:`MIGRATION_MODULES` to
  174. store those modules outside of the app's own module if you wish), or
  175. keep the app with your user model unmigrated.
  176. .. _migration-files:
  177. Migration files
  178. ---------------
  179. Migrations are stored as an on-disk format, referred to here as
  180. "migration files". These files are actually just normal Python files with
  181. an agreed-upon object layout, written in a declarative style.
  182. A basic migration file looks like this::
  183. from django.db import migrations, models
  184. class Migration(migrations.Migration):
  185. dependencies = [("migrations", "0001_initial")]
  186. operations = [
  187. migrations.DeleteModel("Tribble"),
  188. migrations.AddField("Author", "rating", models.IntegerField(default=0)),
  189. ]
  190. What Django looks for when it loads a migration file (as a Python module) is
  191. a subclass of ``django.db.migrations.Migration`` called ``Migration``. It then
  192. inspects this object for four attributes, only two of which are used
  193. most of the time:
  194. * ``dependencies``, a list of migrations this one depends on.
  195. * ``operations``, a list of ``Operation`` classes that define what this
  196. migration does.
  197. The operations are the key; they are a set of declarative instructions which
  198. tell Django what schema changes need to be made. Django scans them and
  199. builds an in-memory representation of all of the schema changes to all apps,
  200. and uses this to generate the SQL which makes the schema changes.
  201. That in-memory structure is also used to work out what the differences are
  202. between your models and the current state of your migrations; Django runs
  203. through all the changes, in order, on an in-memory set of models to come
  204. up with the state of your models last time you ran ``makemigrations``. It
  205. then uses these models to compare against the ones in your ``models.py`` files
  206. to work out what you have changed.
  207. You should rarely, if ever, need to edit migration files by hand, but
  208. it's entirely possible to write them manually if you need to. Some of the
  209. more complex operations are not autodetectable and are only available via
  210. a hand-written migration, so don't be scared about editing them if you have to.
  211. Custom fields
  212. ~~~~~~~~~~~~~
  213. You can't modify the number of positional arguments in an already migrated
  214. custom field without raising a ``TypeError``. The old migration will call the
  215. modified ``__init__`` method with the old signature. So if you need a new
  216. argument, please create a keyword argument and add something like
  217. ``assert kwargs.get('argument_name') is not None`` in the constructor.
  218. Adding migrations to apps
  219. -------------------------
  220. Adding migrations to new apps is straightforward - they come preconfigured to
  221. accept migrations, and so just run :djadmin:`makemigrations` once you've made
  222. some changes.
  223. If your app already has models and database tables, and doesn't have migrations
  224. yet (for example, you created it against a previous Django version), you'll
  225. need to convert it to use migrations; this is a simple process::
  226. $ python manage.py makemigrations your_app_label
  227. This will make a new initial migration for your app. Now, when you run
  228. :djadmin:`migrate`, Django will detect that you have an initial migration
  229. *and* that the tables it wants to create already exist, and will mark the
  230. migration as already applied.
  231. Note that this only works given two things:
  232. * You have not changed your models since you made their tables. For migrations
  233. to work, you must make the initial migration *first* and then make changes,
  234. as Django compares changes against migration files, not the database.
  235. * You have not manually edited your database - Django won't be able to detect
  236. that your database doesn't match your models, you'll just get errors when
  237. migrations try to modify those tables.
  238. .. versionadded:: 1.8
  239. If you want to give the migration(s) a meaningful name instead of a generated one,
  240. you can use the :djadminopt:`--name` option::
  241. $ python manage.py makemigrations --name changed_my_model your_app_label
  242. .. _historical-models:
  243. Historical models
  244. -----------------
  245. When you run migrations, Django is working from historical versions of
  246. your models stored in the migration files. If you write Python code
  247. using the :class:`~django.db.migrations.operations.RunPython` operation, or if
  248. you have ``allow_migrate`` methods on your database routers, you will be
  249. exposed to these versions of your models.
  250. Because it's impossible to serialize arbitrary Python code, these historical
  251. models will not have any custom methods or managers that you have defined.
  252. They will, however, have the same fields, relationships and ``Meta`` options
  253. (also versioned, so they may be different from your current ones).
  254. .. warning::
  255. This means that you will NOT have custom ``save()`` methods called on objects
  256. when you access them in migrations, and you will NOT have any custom
  257. constructors or instance methods. Plan appropriately!
  258. References to functions in field options such as ``upload_to`` and
  259. ``limit_choices_to`` are serialized in migrations, so the functions will need
  260. to be kept around for as long as there is a migration referencing them. Any
  261. :doc:`custom model fields </howto/custom-model-fields>` will also need to be
  262. kept, since these are imported directly by migrations.
  263. In addition, the base classes of the model are just stored as pointers,
  264. so you must always keep base classes around for as long as there is a migration
  265. that contains a reference to them. On the plus side, methods and managers
  266. from these base classes inherit normally, so if you absolutely need access
  267. to these you can opt to move them into a superclass.
  268. .. _data-migrations:
  269. Data Migrations
  270. ---------------
  271. As well as changing the database schema, you can also use migrations to change
  272. the data in the database itself, in conjunction with the schema if you want.
  273. Migrations that alter data are usually called "data migrations"; they're best
  274. written as separate migrations, sitting alongside your schema migrations.
  275. Django can't automatically generate data migrations for you, as it does with
  276. schema migrations, but it's not very hard to write them. Migration files in
  277. Django are made up of :doc:`Operations </ref/migration-operations>`, and
  278. the main operation you use for data migrations is
  279. :class:`~django.db.migrations.operations.RunPython`.
  280. To start, make an empty migration file you can work from (Django will put
  281. the file in the right place, suggest a name, and add dependencies for you)::
  282. python manage.py makemigrations --empty yourappname
  283. Then, open up the file; it should look something like this::
  284. # -*- coding: utf-8 -*-
  285. from django.db import models, migrations
  286. class Migration(migrations.Migration):
  287. dependencies = [
  288. ('yourappname', '0001_initial'),
  289. ]
  290. operations = [
  291. ]
  292. Now, all you need to do is create a new function and have
  293. :class:`~django.db.migrations.operations.RunPython` use it.
  294. :class:`~django.db.migrations.operations.RunPython` expects a callable as its argument
  295. which takes two arguments - the first is an :doc:`app registry
  296. </ref/applications/>` that has the historical versions of all your models
  297. loaded into it to match where in your history the migration sits, and the
  298. second is a :doc:`SchemaEditor </ref/schema-editor>`, which you can use to
  299. manually effect database schema changes (but beware, doing this can confuse
  300. the migration autodetector!)
  301. Let's write a simple migration that populates our new ``name`` field with the
  302. combined values of ``first_name`` and ``last_name`` (we've come to our senses
  303. and realized that not everyone has first and last names). All we
  304. need to do is use the historical model and iterate over the rows::
  305. # -*- coding: utf-8 -*-
  306. from django.db import models, migrations
  307. def combine_names(apps, schema_editor):
  308. # We can't import the Person model directly as it may be a newer
  309. # version than this migration expects. We use the historical version.
  310. Person = apps.get_model("yourappname", "Person")
  311. for person in Person.objects.all():
  312. person.name = "%s %s" % (person.first_name, person.last_name)
  313. person.save()
  314. class Migration(migrations.Migration):
  315. dependencies = [
  316. ('yourappname', '0001_initial'),
  317. ]
  318. operations = [
  319. migrations.RunPython(combine_names),
  320. ]
  321. Once that's done, we can just run ``python manage.py migrate`` as normal and
  322. the data migration will run in place alongside other migrations.
  323. You can pass a second callable to
  324. :class:`~django.db.migrations.operations.RunPython` to run whatever logic you
  325. want executed when migrating backwards. If this callable is omitted, migrating
  326. backwards will raise an exception.
  327. If you're interested in the more advanced migration operations, or want
  328. to be able to write your own, see the :doc:`migration operations reference
  329. </ref/migration-operations>`.
  330. .. _migration-squashing:
  331. Squashing migrations
  332. --------------------
  333. You are encouraged to make migrations freely and not worry about how many you
  334. have; the migration code is optimized to deal with hundreds at a time without
  335. much slowdown. However, eventually you will want to move back from having
  336. several hundred migrations to just a few, and that's where squashing comes in.
  337. Squashing is the act of reducing an existing set of many migrations down to
  338. one (or sometimes a few) migrations which still represent the same changes.
  339. Django does this by taking all of your existing migrations, extracting their
  340. ``Operation``\s and putting them all in sequence, and then running an optimizer
  341. over them to try and reduce the length of the list - for example, it knows
  342. that :class:`~django.db.migrations.operations.CreateModel` and
  343. :class:`~django.db.migrations.operations.DeleteModel` cancel each other out,
  344. and it knows that :class:`~django.db.migrations.operations.AddField` can be
  345. rolled into :class:`~django.db.migrations.operations.CreateModel`.
  346. Once the operation sequence has been reduced as much as possible - the amount
  347. possible depends on how closely intertwined your models are and if you have
  348. any :class:`~django.db.migrations.operations.RunSQL`
  349. or :class:`~django.db.migrations.operations.RunPython` operations (which can't
  350. be optimized through) - Django will them write it back out into a new set of
  351. initial migration files.
  352. These files are marked to say they replace the previously-squashed migrations,
  353. so they can coexist with the old migration files, and Django will intelligently
  354. switch between them depending where you are in the history. If you're still
  355. part-way through the set of migrations that you squashed, it will keep using
  356. them until it hits the end and then switch to the squashed history, while new
  357. installs will just use the new squashed migration and skip all the old ones.
  358. This enables you to squash and not mess up systems currently in production
  359. that aren't fully up-to-date yet. The recommended process is to squash, keeping
  360. the old files, commit and release, wait until all systems are upgraded with
  361. the new release (or if you're a third-party project, just ensure your users
  362. upgrade releases in order without skipping any), and then remove the old files,
  363. commit and do a second release.
  364. The command that backs all this is :djadmin:`squashmigrations` - just pass
  365. it the app label and migration name you want to squash up to, and it'll get to
  366. work::
  367. $ ./manage.py squashmigrations myapp 0004
  368. Will squash the following migrations:
  369. - 0001_initial
  370. - 0002_some_change
  371. - 0003_another_change
  372. - 0004_undo_something
  373. Do you wish to proceed? [yN] y
  374. Optimizing...
  375. Optimized from 12 operations to 7 operations.
  376. Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_somthing.py
  377. You should commit this migration but leave the old ones in place;
  378. the new migration will be used for new installs. Once you are sure
  379. all instances of the codebase have applied the migrations you squashed,
  380. you can delete them.
  381. Note that model interdependencies in Django can get very complex, and squashing
  382. may result in migrations that do not run; either mis-optimized (in which case
  383. you can try again with ``--no-optimize``, though you should also report an issue),
  384. or with a ``CircularDependencyError``, in which case you can manually resolve it.
  385. To manually resolve a ``CircularDependencyError``, break out one of
  386. the ForeignKeys in the circular dependency loop into a separate
  387. migration, and move the dependency on the other app with it. If you're unsure,
  388. see how makemigrations deals with the problem when asked to create brand
  389. new migrations from your models. In a future release of Django, squashmigrations
  390. will be updated to attempt to resolve these errors itself.
  391. Once you've squashed your migration, you should then commit it alongside the
  392. migrations it replaces and distribute this change to all running instances
  393. of your application, making sure that they run ``migrate`` to store the change
  394. in their database.
  395. After this has been done, you must then transition the squashed migration to
  396. a normal initial migration, by:
  397. - Deleting all the migration files it replaces
  398. - Removing the ``replaces`` argument in the ``Migration`` class of the
  399. squashed migration (this is how Django tells that it is a squashed migration)
  400. .. note::
  401. Once you've squashed a migration, you should not then re-squash that squashed
  402. migration until you have fully transitioned it to a normal migration.
  403. .. _migration-serializing:
  404. Serializing values
  405. ------------------
  406. Migrations are just Python files containing the old definitions of your models
  407. - thus, to write them, Django must take the current state of your models and
  408. serialize them out into a file.
  409. While Django can serialize most things, there are some things that we just
  410. can't serialize out into a valid Python representation - there's no Python
  411. standard for how a value can be turned back into code (``repr()`` only works
  412. for basic values, and doesn't specify import paths).
  413. Django can serialize the following:
  414. - ``int``, ``long``, ``float``, ``bool``, ``str``, ``unicode``, ``bytes``, ``None``
  415. - ``list``, ``set``, ``tuple``, ``dict``
  416. - ``datetime.date``, ``datetime.time``, and ``datetime.datetime`` instances
  417. - ``decimal.Decimal`` instances
  418. - Any Django field
  419. - Any function or method reference (e.g. ``datetime.datetime.today``) (must be in module's top-level scope)
  420. - Any class reference (must be in module's top-level scope)
  421. - Anything with a custom ``deconstruct()`` method (:ref:`see below <custom-deconstruct-method>`)
  422. Django can serialize the following on Python 3 only:
  423. - Unbound methods used from within the class body (see below)
  424. Django cannot serialize:
  425. - Nested classes
  426. - Arbitrary class instances (e.g. ``MyClass(4.3, 5.7)``)
  427. - Lambdas
  428. Due to the fact ``__qualname__`` was only introduced in Python 3, Django can only
  429. serialize the following pattern (an unbound method used within the class body)
  430. on Python 3, and will fail to serialize a reference to it on Python 2::
  431. class MyModel(models.Model):
  432. def upload_to(self):
  433. return "something dynamic"
  434. my_file = models.FileField(upload_to=upload_to)
  435. If you are using Python 2, we recommend you move your methods for upload_to
  436. and similar arguments that accept callables (e.g. ``default``) to live in
  437. the main module body, rather than the class body.
  438. .. _custom-deconstruct-method:
  439. Adding a deconstruct() method
  440. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  441. You can let Django serialize your own custom class instances by giving the class
  442. a ``deconstruct()`` method. It takes no arguments, and should return a tuple
  443. of three things ``(path, args, kwargs)``:
  444. * ``path`` should be the Python path to the class, with the class name included
  445. as the last part (for example, ``myapp.custom_things.MyClass``). If your
  446. class is not available at the top level of a module it is not serializable.
  447. * ``args`` should be a list of positional arguments to pass to your class'
  448. ``__init__`` method. Everything in this list should itself be serializable.
  449. * ``kwargs`` should be a dict of keyword arguments to pass to your class'
  450. ``__init__`` method. Every value should itself be serializable.
  451. .. note::
  452. This return value is different from the ``deconstruct()`` method
  453. :ref:`for custom fields <custom-field-deconstruct-method>` which returns a
  454. tuple of four items.
  455. Django will write out the value as an instantiation of your class with the
  456. given arguments, similar to the way it writes out references to Django fields.
  457. To prevent a new migration from being created each time
  458. :djadmin:`makemigrations` is run, you should also add a ``__eq__()`` method to
  459. the decorated class. This function will be called by Django's migration
  460. framework to detect changes between states.
  461. As long as all of the arguments to your class' constructor are themselves
  462. serializable, you can use the ``@deconstructible`` class decorator from
  463. ``django.utils.deconstruct`` to add the ``deconstruct()`` method::
  464. from django.utils.deconstruct import deconstructible
  465. @deconstructible
  466. class MyCustomClass(object):
  467. def __init__(self, foo=1):
  468. self.foo = foo
  469. ...
  470. def __eq__(self, other):
  471. return self.foo == other.foo
  472. The decorator adds logic to capture and preserve the arguments on their
  473. way into your constructor, and then returns those arguments exactly when
  474. deconstruct() is called.
  475. .. _upgrading-from-south:
  476. Upgrading from South
  477. --------------------
  478. If you already have pre-existing migrations created with
  479. `South <http://south.aeracode.org>`_, then the upgrade process to use
  480. ``django.db.migrations`` is quite simple:
  481. * Ensure all installs are fully up-to-date with their migrations.
  482. * Remove ``'south'`` from :setting:`INSTALLED_APPS`.
  483. * Delete all your (numbered) migration files, but not the directory or
  484. ``__init__.py`` - make sure you remove the ``.pyc`` files too.
  485. * Run ``python manage.py makemigrations``. Django should see the empty
  486. migration directories and make new initial migrations in the new format.
  487. * Run ``python manage.py migrate``. Django will see that the tables for the
  488. initial migrations already exist and mark them as applied without running
  489. them.
  490. That's it! The only complication is if you have a circular dependency loop
  491. of foreign keys; in this case, ``makemigrations`` might make more than one
  492. initial migration, and you'll need to mark them all as applied using::
  493. python manage.py migrate --fake yourappnamehere
  494. Libraries/Third-party Apps
  495. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  496. If you are a library or app maintainer, and wish to support both South migrations
  497. (for Django 1.6 and below) and Django migrations (for 1.7 and above) you should
  498. keep two parallel migration sets in your app, one in each format.
  499. To aid in this, South 1.0 will automatically look for South-format migrations
  500. in a ``south_migrations`` directory first, before looking in ``migrations``,
  501. meaning that users' projects will transparently use the correct set as long
  502. as you put your South migrations in the ``south_migrations`` directory and
  503. your Django migrations in the ``migrations`` directory.
  504. More information is available in the
  505. `South 1.0 release notes <http://south.readthedocs.org/en/latest/releasenotes/1.0.html#library-migration-path>`_.
  506. .. seealso::
  507. :doc:`The Migrations Operations Reference </ref/migration-operations>`
  508. Covers the schema operations API, special operations, and writing your
  509. own operations.