migrations.txt 34 KB

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