{"title":"Migracje","version":"5.2","locale":"pl","docname":"topics/migrations","url":"/pl/5.2/topics/migrations/","canonical":"https://djangodocs.dev/pl/5.2/topics/migrations/","summary":"Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to…","html":"<span id=\"migrations\"></span><h1>Migracje<a class=\"heading-anchor\" href=\"#module-django.db.migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>Migrations are Django’s way of propagating changes you make to your models\n(adding a field, deleting a model, etc.) into your database schema. They’re\ndesigned to be mostly automatic, but you’ll need to know when to make\nmigrations, when to run them, and the common problems you might run into.</p>\n<section id=\"the-commands\">\n<h2>The Commands<a class=\"heading-anchor\" href=\"#the-commands\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>There are several commands which you will use to interact with migrations\nand Django’s handling of database schema:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">migrate</span></code></a>, which is responsible for applying and unapplying\nmigrations.</p></li>\n<li><p><a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a>, which is responsible for creating new migrations\nbased on the changes you have made to your models.</p></li>\n<li><p><a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-sqlmigrate\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">sqlmigrate</span></code></a>, which displays the SQL statements for a migration.</p></li>\n<li><p><a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-showmigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">showmigrations</span></code></a>, which lists a project’s migrations and their\nstatus.</p></li>\n</ul>\n<p>You should think of migrations as a version control system for your database\nschema. <code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> is responsible for packaging up your model changes\ninto individual migration files - analogous to commits - and <code class=\"docutils literal notranslate\"><span class=\"pre\">migrate</span></code> is\nresponsible for applying those to your database.</p>\n<p>The migration files for each app live in a „migrations” directory inside\nof that app, and are designed to be committed to, and distributed as part\nof, its codebase. You should be making them once on your development machine\nand then running the same migrations on your colleagues» machines, your\nstaging machines, and eventually your production machines.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Informacja</p>\n<p>It is possible to override the name of the package which contains the\nmigrations on a per-app basis by modifying the <a class=\"reference internal\" href=\"/pl/5.2/ref/settings/#std-setting-MIGRATION_MODULES\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">MIGRATION_MODULES</span></code></a>\nsetting.</p>\n</aside>\n<p>Migrations will run the same way on the same dataset and produce consistent\nresults, meaning that what you see in development and staging is, under the\nsame circumstances, exactly what will happen in production.</p>\n<p>Django will make migrations for any change to your models or fields - even\noptions that don’t affect the database - as the only way it can reconstruct\na field correctly is to have all the changes in the history, and you might\nneed those options in some data migrations later on (for example, if you’ve\nset custom validators).</p>\n</section>\n<section id=\"backend-support\">\n<h2>Backend Support<a class=\"heading-anchor\" href=\"#backend-support\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations are supported on all backends that Django ships with, as well\nas any third-party backends if they have programmed in support for schema\nalteration (done via the <a class=\"reference internal\" href=\"/pl/5.2/ref/schema-editor/\"><span class=\"doc\">SchemaEditor</span></a> class).</p>\n<p>However, some databases are more capable than others when it comes to\nschema migrations; some of the caveats are covered below.</p>\n<section id=\"postgresql\">\n<h3>PostgreSQL<a class=\"heading-anchor\" href=\"#postgresql\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>PostgreSQL is the most capable of all the databases here in terms of schema\nsupport.</p>\n</section>\n<section id=\"mysql\">\n<h3>MySQL<a class=\"heading-anchor\" href=\"#mysql\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>MySQL lacks support for transactions around schema alteration operations,\nmeaning that if a migration fails to apply you will have to manually unpick\nthe changes in order to try again (it’s impossible to roll back to an\nearlier point).</p>\n<p>MySQL 8.0 introduced significant performance enhancements for\n<a class=\"reference external\" href=\"https://dev.mysql.com/doc/refman/en/innodb-online-ddl-operations.html\">DDL operations</a>, making them more efficient and reducing the need for full\ntable rebuilds. However, it cannot guarantee a complete absence of locks or\ninterruptions. In situations where locks are still necessary, the duration of\nthese operations will be proportionate to the number of rows involved.</p>\n<p>Finally, MySQL has a relatively small limit on the combined size of all columns\nan index covers. This means that indexes that are possible on other backends\nwill fail to be created under MySQL.</p>\n</section>\n<section id=\"sqlite\">\n<h3>SQLite<a class=\"heading-anchor\" href=\"#sqlite\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>SQLite has very little built-in schema alteration support, and so Django\nattempts to emulate it by:</p>\n<ul class=\"simple\">\n<li><p>Creating a new table with the new schema</p></li>\n<li><p>Copying the data across</p></li>\n<li><p>Dropping the old table</p></li>\n<li><p>Renaming the new table to match the original name</p></li>\n</ul>\n<p>This process generally works well, but it can be slow and occasionally\nbuggy. It is not recommended that you run and migrate SQLite in a\nproduction environment unless you are very aware of the risks and\nits limitations; the support Django ships with is designed to allow\ndevelopers to use SQLite on their local machines to develop less complex\nDjango projects without the need for a full database.</p>\n</section>\n</section>\n<section id=\"workflow\">\n<h2>Workflow<a class=\"heading-anchor\" href=\"#workflow\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django can create migrations for you. Make changes to your models - say, add a\nfield and remove a model - and then run <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a>:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code>$<span class=\"w\"> </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>makemigrations\nMigrations<span class=\"w\"> </span><span class=\"k\">for</span><span class=\"w\"> </span><span class=\"s1\">&#39;books&#39;</span>:\n<span class=\"w\">  </span>books/migrations/0003_auto.py:\n<span class=\"w\">    </span>~<span class=\"w\"> </span>Alter<span class=\"w\"> </span>field<span class=\"w\"> </span>author<span class=\"w\"> </span>on<span class=\"w\"> </span>book\n</code></pre></div>\n<p>Your models will be scanned and compared to the versions currently\ncontained in your migration files, and then a new set of migrations\nwill be written out. Make sure to read the output to see what\n<code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> thinks you have changed - it’s not perfect, and for\ncomplex changes it might not be detecting what you expect.</p>\n<p>Once you have your new migration files, you should apply them to your\ndatabase to make sure they work as expected:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code>$<span class=\"w\"> </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate\nOperations<span class=\"w\"> </span>to<span class=\"w\"> </span>perform:\n<span class=\"w\">  </span>Apply<span class=\"w\"> </span>all<span class=\"w\"> </span>migrations:<span class=\"w\"> </span>books\nRunning<span class=\"w\"> </span>migrations:\n<span class=\"w\">  </span>Rendering<span class=\"w\"> </span>model<span class=\"w\"> </span>states...<span class=\"w\"> </span>DONE\n<span class=\"w\">  </span>Applying<span class=\"w\"> </span>books.0003_auto...<span class=\"w\"> </span>OK\n</code></pre></div>\n<p>Once the migration is applied, commit the migration and the models change\nto your version control system as a single commit - that way, when other\ndevelopers (or your production servers) check out the code, they’ll\nget both the changes to your models and the accompanying migration at the\nsame time.</p>\n<p>If you want to give the migration(s) a meaningful name instead of a generated\none, you can use the <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#cmdoption-makemigrations-name\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">makemigrations</span> <span class=\"pre\">--name</span></code></a> option:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code>$<span class=\"w\"> </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>makemigrations<span class=\"w\"> </span>--name<span class=\"w\"> </span>changed_my_model<span class=\"w\"> </span>your_app_label\n</code></pre></div>\n<section id=\"version-control\">\n<h3>Kontrola wersji<a class=\"heading-anchor\" href=\"#version-control\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Because migrations are stored in version control, you’ll occasionally\ncome across situations where you and another developer have both committed\na migration to the same app at the same time, resulting in two migrations\nwith the same number.</p>\n<p>Don’t worry - the numbers are just there for developers» reference, Django\njust cares that each migration has a different name. Migrations specify which\nother migrations they depend on - including earlier migrations in the same\napp - in the file, so it’s possible to detect when there’s two new migrations\nfor the same app that aren’t ordered.</p>\n<p>When this happens, Django will prompt you and give you some options. If it\nthinks it’s safe enough, it will offer to automatically linearize the two\nmigrations for you. If not, you’ll have to go in and modify the migrations\nyourself - don’t worry, this isn’t difficult, and is explained more in\n<a class=\"reference internal\" href=\"#migration-files\"><span class=\"std std-ref\">Pliki migracji</span></a> below.</p>\n</section>\n</section>\n<section id=\"transactions\">\n<h2>Transactions<a class=\"heading-anchor\" href=\"#transactions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>On databases that support DDL transactions (SQLite and PostgreSQL), all\nmigration operations will run inside a single transaction by default. In\ncontrast, if a database doesn’t support DDL transactions (e.g. MySQL, Oracle)\nthen all operations will run without a transaction.</p>\n<p>You can prevent a migration from running in a transaction by setting the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">atomic</span></code> attribute to <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code>. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">migrations</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n    <span class=\"n\">atomic</span> <span class=\"o\">=</span> <span class=\"kc\">False</span>\n</code></pre></div>\n<p>It’s also possible to execute parts of the migration inside a transaction using\n<a class=\"reference internal\" href=\"/pl/5.2/topics/db/transactions/#django.db.transaction.atomic\" title=\"django.db.transaction.atomic\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">atomic()</span></code></a> or by passing <code class=\"docutils literal notranslate\"><span class=\"pre\">atomic=True</span></code> to\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a>. See\n<a class=\"reference internal\" href=\"/pl/5.2/howto/writing-migrations/#non-atomic-migrations\"><span class=\"std std-ref\">Niezatomizowane migracje</span></a> for more details.</p>\n</section>\n<section id=\"dependencies\">\n<h2>Zależności<a class=\"heading-anchor\" href=\"#dependencies\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>While migrations are per-app, the tables and relationships implied by\nyour models are too complex to be created for one app at a time. When you make\na migration that requires something else to run - for example, you add a\n<code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> in your <code class=\"docutils literal notranslate\"><span class=\"pre\">books</span></code> app to your <code class=\"docutils literal notranslate\"><span class=\"pre\">authors</span></code> app - the resulting\nmigration will contain a dependency on a migration in <code class=\"docutils literal notranslate\"><span class=\"pre\">authors</span></code>.</p>\n<p>This means that when you run the migrations, the <code class=\"docutils literal notranslate\"><span class=\"pre\">authors</span></code> migration runs\nfirst and creates the table the <code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> references, and then the migration\nthat makes the <code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code> column runs afterward and creates the constraint.\nIf this didn’t happen, the migration would try to create the <code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code>\ncolumn without the table it’s referencing existing and your database would\nthrow an error.</p>\n<p>This dependency behavior affects most migration operations where you\nrestrict to a single app. Restricting to a single app (either in\n<code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code> or <code class=\"docutils literal notranslate\"><span class=\"pre\">migrate</span></code>) is a best-efforts promise, and not\na guarantee; any other apps that need to be used to get dependencies correct\nwill be.</p>\n<p>Apps without migrations must not have relations (<code class=\"docutils literal notranslate\"><span class=\"pre\">ForeignKey</span></code>,\n<code class=\"docutils literal notranslate\"><span class=\"pre\">ManyToManyField</span></code>, etc.) to apps with migrations. Sometimes it may work, but\nit’s not supported.</p>\n<section id=\"swappable-dependencies\">\n<h3>Swappable dependencies<a class=\"heading-anchor\" href=\"#swappable-dependencies\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.db.migrations.django.db.migrations.swappable_dependency\">\n<span class=\"sig-prename descclassname\"><span class=\"pre\">django.db.migrations.</span></span><span class=\"sig-name descname\"><span class=\"pre\">swappable_dependency</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">value</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.migrations.django.db.migrations.swappable_dependency\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">swappable_dependency()</span></code> function is used in migrations to declare\n„swappable” dependencies on migrations in the app of the swapped-in model,\ncurrently, on the first migration of this app. As a consequence, the swapped-in\nmodel should be created in the initial migration. The argument <code class=\"docutils literal notranslate\"><span class=\"pre\">value</span></code> is a\nstring <code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;&lt;app</span> <span class=\"pre\">label&gt;.&lt;model&gt;&quot;</span></code> describing an app label and a model name, e.g.\n<code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;myapp.MyModel&quot;</span></code>.</p>\n<p>By using <code class=\"docutils literal notranslate\"><span class=\"pre\">swappable_dependency()</span></code>, you inform the migration framework that\nthe migration relies on another migration which sets up a swappable model,\nallowing for the possibility of substituting the model with a different\nimplementation in the future. This is typically used for referencing models\nthat are subject to customization or replacement, such as the custom user\nmodel (<code class=\"docutils literal notranslate\"><span class=\"pre\">settings.AUTH_USER_MODEL</span></code>, which defaults to <code class=\"docutils literal notranslate\"><span class=\"pre\">&quot;auth.User&quot;</span></code>) in\nDjango’s authentication system.</p>\n</section>\n</section>\n<section id=\"migration-files\">\n<span id=\"id1\"></span><h2>Pliki migracji<a class=\"heading-anchor\" href=\"#migration-files\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations are stored as an on-disk format, referred to here as\n„migration files”. These files are actually normal Python files with an\nagreed-upon object layout, written in a declarative style.</p>\n<p>A basic migration file looks like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">migrations</span><span class=\"p\">,</span> <span class=\"n\">models</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[(</span><span class=\"s2\">&quot;migrations&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;0001_initial&quot;</span><span class=\"p\">)]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">DeleteModel</span><span class=\"p\">(</span><span class=\"s2\">&quot;Tribble&quot;</span><span class=\"p\">),</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">AddField</span><span class=\"p\">(</span><span class=\"s2\">&quot;Author&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;rating&quot;</span><span class=\"p\">,</span> <span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">IntegerField</span><span class=\"p\">(</span><span class=\"n\">default</span><span class=\"o\">=</span><span class=\"mi\">0</span><span class=\"p\">)),</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n<p>What Django looks for when it loads a migration file (as a Python module) is\na subclass of <code class=\"docutils literal notranslate\"><span class=\"pre\">django.db.migrations.Migration</span></code> called <code class=\"docutils literal notranslate\"><span class=\"pre\">Migration</span></code>. It then\ninspects this object for four attributes, only two of which are used\nmost of the time:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">dependencies</span></code>, a list of migrations this one depends on.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">operations</span></code>, a list of <code class=\"docutils literal notranslate\"><span class=\"pre\">Operation</span></code> classes that define what this\nmigration does.</p></li>\n</ul>\n<p>The operations are the key; they are a set of declarative instructions which\ntell Django what schema changes need to be made. Django scans them and\nbuilds an in-memory representation of all of the schema changes to all apps,\nand uses this to generate the SQL which makes the schema changes.</p>\n<p>That in-memory structure is also used to work out what the differences are\nbetween your models and the current state of your migrations; Django runs\nthrough all the changes, in order, on an in-memory set of models to come\nup with the state of your models last time you ran <code class=\"docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code>. It\nthen uses these models to compare against the ones in your <code class=\"docutils literal notranslate\"><span class=\"pre\">models.py</span></code> files\nto work out what you have changed.</p>\n<p>You should rarely, if ever, need to edit migration files by hand, but\nit’s entirely possible to write them manually if you need to. Some of the\nmore complex operations are not autodetectable and are only available via\na hand-written migration, so don’t be scared about editing them if you have to.</p>\n<section id=\"custom-fields\">\n<h3>Custom fields<a class=\"heading-anchor\" href=\"#custom-fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You can’t modify the number of positional arguments in an already migrated\ncustom field without raising a <code class=\"docutils literal notranslate\"><span class=\"pre\">TypeError</span></code>. The old migration will call the\nmodified <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span></code> method with the old signature. So if you need a new\nargument, please create a keyword argument and add something like\n<code class=\"docutils literal notranslate\"><span class=\"pre\">assert</span> <span class=\"pre\">'argument_name'</span> <span class=\"pre\">in</span> <span class=\"pre\">kwargs</span></code> in the constructor.</p>\n</section>\n<section id=\"model-managers\">\n<span id=\"using-managers-in-migrations\"></span><h3>Zarządcy modeli<a class=\"heading-anchor\" href=\"#model-managers\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You can optionally serialize managers into migrations and have them available\nin <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> operations. This is done\nby defining a <code class=\"docutils literal notranslate\"><span class=\"pre\">use_in_migrations</span></code> attribute on the manager class:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyManager</span><span class=\"p\">(</span><span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">Manager</span><span class=\"p\">):</span>\n    <span class=\"n\">use_in_migrations</span> <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyModel</span><span class=\"p\">(</span><span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">Model</span><span class=\"p\">):</span>\n    <span class=\"n\">objects</span> <span class=\"o\">=</span> <span class=\"n\">MyManager</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>If you are using the <a class=\"reference internal\" href=\"/pl/5.2/topics/db/managers/#django.db.models.from_queryset\" title=\"django.db.models.from_queryset\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">from_queryset()</span></code></a> function to\ndynamically generate a manager class, you need to inherit from the generated\nclass to make it importable:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyManager</span><span class=\"p\">(</span><span class=\"n\">MyBaseManager</span><span class=\"o\">.</span><span class=\"n\">from_queryset</span><span class=\"p\">(</span><span class=\"n\">CustomQuerySet</span><span class=\"p\">)):</span>\n    <span class=\"n\">use_in_migrations</span> <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyModel</span><span class=\"p\">(</span><span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">Model</span><span class=\"p\">):</span>\n    <span class=\"n\">objects</span> <span class=\"o\">=</span> <span class=\"n\">MyManager</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>Please refer to the notes about <a class=\"reference internal\" href=\"#historical-models\"><span class=\"std std-ref\">Modele historyczne</span></a> in migrations to see\nthe implications that come along.</p>\n</section>\n<section id=\"initial-migrations\">\n<h3>Initial migrations<a class=\"heading-anchor\" href=\"#initial-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.db.migrations.Migration.initial\">\n<span class=\"sig-prename descclassname\"><span class=\"pre\">Migration.</span></span><span class=\"sig-name descname\"><span class=\"pre\">initial</span></span><a class=\"heading-anchor\" href=\"#django.db.migrations.Migration.initial\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The „initial migrations” for an app are the migrations that create the first\nversion of that app’s tables. Usually an app will have one initial migration,\nbut in some cases of complex model interdependencies it may have two or more.</p>\n<p>Initial migrations are marked with an <code class=\"docutils literal notranslate\"><span class=\"pre\">initial</span> <span class=\"pre\">=</span> <span class=\"pre\">True</span></code> class attribute on the\nmigration class. If an <code class=\"docutils literal notranslate\"><span class=\"pre\">initial</span></code> class attribute isn’t found, a migration\nwill be considered „initial” if it is the first migration in the app (i.e. if\nit has no dependencies on any other migration in the same app).</p>\n<p>When the <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#cmdoption-migrate-fake-initial\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">migrate</span> <span class=\"pre\">--fake-initial</span></code></a> option is used, these initial\nmigrations are treated specially. For an initial migration that creates one or\nmore tables (<code class=\"docutils literal notranslate\"><span class=\"pre\">CreateModel</span></code> operation), Django checks that all of those tables\nalready exist in the database and fake-applies the migration if so. Similarly,\nfor an initial migration that adds one or more fields (<code class=\"docutils literal notranslate\"><span class=\"pre\">AddField</span></code> operation),\nDjango checks that all of the respective columns already exist in the database\nand fake-applies the migration if so. Without <code class=\"docutils literal notranslate\"><span class=\"pre\">--fake-initial</span></code>, initial\nmigrations are treated no differently from any other migration.</p>\n</section>\n<section id=\"history-consistency\">\n<span id=\"migration-history-consistency\"></span><h3>History consistency<a class=\"heading-anchor\" href=\"#history-consistency\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>As previously discussed, you may need to linearize migrations manually when two\ndevelopment branches are joined. While editing migration dependencies, you can\ninadvertently create an inconsistent history state where a migration has been\napplied but some of its dependencies haven’t. This is a strong indication that\nthe dependencies are incorrect, so Django will refuse to run migrations or make\nnew migrations until it’s fixed. When using multiple databases, you can use the\n<a class=\"reference internal\" href=\"/pl/5.2/topics/db/multi-db/#allow_migrate\" title=\"allow_migrate\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">allow_migrate()</span></code></a> method of <a class=\"reference internal\" href=\"/pl/5.2/topics/db/multi-db/#topics-db-multi-db-routing\"><span class=\"std std-ref\">database routers</span></a> to control which databases\n<a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> checks for consistent history.</p>\n</section>\n</section>\n<section id=\"adding-migrations-to-apps\">\n<h2>Dodawanie migracji do aplikacji<a class=\"heading-anchor\" href=\"#adding-migrations-to-apps\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>New apps come preconfigured to accept migrations, and so you can add migrations\nby running <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> once you’ve made some changes.</p>\n<p>If your app already has models and database tables, and doesn’t have migrations\nyet (for example, you created it against a previous Django version), you’ll\nneed to convert it to use migrations by running:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code>$<span class=\"w\"> </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>makemigrations<span class=\"w\"> </span>your_app_label\n</code></pre></div>\n<p>This will make a new initial migration for your app. Now, run <code class=\"docutils literal notranslate\"><span class=\"pre\">python</span>\n<span class=\"pre\">manage.py</span> <span class=\"pre\">migrate</span> <span class=\"pre\">--fake-initial</span></code>, and Django will detect that you have an\ninitial migration <em>and</em> that the tables it wants to create already exist, and\nwill mark the migration as already applied. (Without the <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#cmdoption-migrate-fake-initial\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">migrate</span>\n<span class=\"pre\">--fake-initial</span></code></a> flag, the command would error out because the tables it wants\nto create already exist.)</p>\n<p>Zauważ, że to tylko działa pod dwoma warunkami:</p>\n<ul class=\"simple\">\n<li><p>You have not changed your models since you made their tables. For migrations\nto work, you must make the initial migration <em>first</em> and then make changes,\nas Django compares changes against migration files, not the database.</p></li>\n<li><p>You have not manually edited your database - Django won’t be able to detect\nthat your database doesn’t match your models, you’ll just get errors when\nmigrations try to modify those tables.</p></li>\n</ul>\n</section>\n<section id=\"reversing-migrations\">\n<span id=\"id2\"></span><h2>Reversing migrations<a class=\"heading-anchor\" href=\"#reversing-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations can be reversed with <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">migrate</span></code></a> by passing the number of the\nprevious migration. For example, to reverse migration <code class=\"docutils literal notranslate\"><span class=\"pre\">books.0003</span></code>:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-0-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate<span class=\"w\"> </span>books<span class=\"w\"> </span><span class=\"m\">0002</span>\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto... OK</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-0-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate books 0002\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto... OK</span>\n</code></pre></div></div></div>\n<p>If you want to reverse all migrations applied for an app, use the name\n<code class=\"docutils literal notranslate\"><span class=\"pre\">zero</span></code>:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-1-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate<span class=\"w\"> </span>books<span class=\"w\"> </span>zero\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Unapply all migrations: books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0002_auto... OK</span>\n<span class=\"go\">  Unapplying books.0001_initial... OK</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-1-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate books zero\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Unapply all migrations: books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0002_auto... OK</span>\n<span class=\"go\">  Unapplying books.0001_initial... OK</span>\n</code></pre></div></div></div>\n<p>A migration is irreversible if it contains any irreversible operations.\nAttempting to reverse such migrations will raise <code class=\"docutils literal notranslate\"><span class=\"pre\">IrreversibleError</span></code>:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-2-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>migrate<span class=\"w\"> </span>books<span class=\"w\"> </span><span class=\"m\">0002</span>\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto...Traceback (most recent call last):</span>\n<span class=\"go\">django.db.migrations.exceptions.IrreversibleError: Operation &lt;RunSQL  sql=&#39;DROP TABLE demo_books&#39;&gt; in books.0003_auto is not reversible</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-2-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate books 0002\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Target specific migration: 0002_auto, from books</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Unapplying books.0003_auto...Traceback (most recent call last):</span>\n<span class=\"gp\">django.db.migrations.exceptions.IrreversibleError: Operation &lt;RunSQL  sql=&#39;DROP TABLE demo_books&#39;&gt;</span> in books.0003_auto is not reversible\n</code></pre></div></div></div>\n</section>\n<section id=\"historical-models\">\n<span id=\"id3\"></span><h2>Modele historyczne<a class=\"heading-anchor\" href=\"#historical-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>When you run migrations, Django is working from historical versions of your\nmodels stored in the migration files. If you write Python code using the\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> operation, or if you have\n<code class=\"docutils literal notranslate\"><span class=\"pre\">allow_migrate</span></code> methods on your database routers, you <strong>need to use</strong> these\nhistorical model versions rather than importing them directly.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Ostrzeżenie</p>\n<p>If you import models directly rather than using the historical models,\nyour migrations <em>may work initially</em> but will fail in the future when you\ntry to rerun old migrations (commonly, when you set up a new installation\nand run through all the migrations to set up the database).</p>\n<p>This means that historical model problems may not be immediately obvious.\nIf you run into this kind of failure, it’s OK to edit the migration to use\nthe historical models rather than direct imports and commit those changes.</p>\n</aside>\n<p>Because it’s impossible to serialize arbitrary Python code, these historical\nmodels will not have any custom methods that you have defined. They will,\nhowever, have the same fields, relationships, managers (limited to those with\n<code class=\"docutils literal notranslate\"><span class=\"pre\">use_in_migrations</span> <span class=\"pre\">=</span> <span class=\"pre\">True</span></code>) and <code class=\"docutils literal notranslate\"><span class=\"pre\">Meta</span></code> options (also versioned, so they may\nbe different from your current ones).</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Ostrzeżenie</p>\n<p>This means that you will NOT have custom <code class=\"docutils literal notranslate\"><span class=\"pre\">save()</span></code> methods called on objects\nwhen you access them in migrations, and you will NOT have any custom\nconstructors or instance methods. Plan appropriately!</p>\n</aside>\n<p>References to functions in field options such as <code class=\"docutils literal notranslate\"><span class=\"pre\">upload_to</span></code> and\n<code class=\"docutils literal notranslate\"><span class=\"pre\">limit_choices_to</span></code> and model manager declarations with managers having\n<code class=\"docutils literal notranslate\"><span class=\"pre\">use_in_migrations</span> <span class=\"pre\">=</span> <span class=\"pre\">True</span></code> are serialized in migrations, so the functions and\nclasses will need to be kept around for as long as there is a migration\nreferencing them. Any <a class=\"reference internal\" href=\"/pl/5.2/howto/custom-model-fields/\"><span class=\"doc\">custom model fields</span></a>\nwill also need to be kept, since these are imported directly by migrations.</p>\n<p>In addition, the concrete base classes of the model are stored as pointers, so\nyou must always keep base classes around for as long as there is a migration\nthat contains a reference to them. On the plus side, methods and managers from\nthese base classes inherit normally, so if you absolutely need access to these\nyou can opt to move them into a superclass.</p>\n<p>To remove old references, you can <a class=\"reference internal\" href=\"#migration-squashing\"><span class=\"std std-ref\">squash migrations</span></a>\nor, if there aren’t many references, copy them into the migration files.</p>\n</section>\n<section id=\"considerations-when-removing-model-fields\">\n<span id=\"migrations-removing-model-fields\"></span><h2>Considerations when removing model fields<a class=\"heading-anchor\" href=\"#considerations-when-removing-model-fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Similar to the „references to historical functions” considerations described in\nthe previous section, removing custom model fields from your project or\nthird-party app will cause a problem if they are referenced in old migrations.</p>\n<p>To help with this situation, Django provides some model field attributes to\nassist with model field deprecation using the <a class=\"reference internal\" href=\"/pl/5.2/topics/checks/\"><span class=\"doc\">system checks framework</span></a>.</p>\n<p>Add the <code class=\"docutils literal notranslate\"><span class=\"pre\">system_check_deprecated_details</span></code> attribute to your model field\nsimilar to the following:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">IPAddressField</span><span class=\"p\">(</span><span class=\"n\">Field</span><span class=\"p\">):</span>\n    <span class=\"n\">system_check_deprecated_details</span> <span class=\"o\">=</span> <span class=\"p\">{</span>\n        <span class=\"s2\">&quot;msg&quot;</span><span class=\"p\">:</span> <span class=\"p\">(</span>\n            <span class=\"s2\">&quot;IPAddressField has been deprecated. Support for it (except &quot;</span>\n            <span class=\"s2\">&quot;in historical migrations) will be removed in Django 1.9.&quot;</span>\n        <span class=\"p\">),</span>\n        <span class=\"s2\">&quot;hint&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;Use GenericIPAddressField instead.&quot;</span><span class=\"p\">,</span>  <span class=\"c1\"># optional</span>\n        <span class=\"s2\">&quot;id&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;fields.W900&quot;</span><span class=\"p\">,</span>  <span class=\"c1\"># pick a unique ID for your field.</span>\n    <span class=\"p\">}</span>\n</code></pre></div>\n<p>After a deprecation period of your choosing (two or three feature releases for\nfields in Django itself), change the <code class=\"docutils literal notranslate\"><span class=\"pre\">system_check_deprecated_details</span></code>\nattribute to <code class=\"docutils literal notranslate\"><span class=\"pre\">system_check_removed_details</span></code> and update the dictionary similar\nto:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">IPAddressField</span><span class=\"p\">(</span><span class=\"n\">Field</span><span class=\"p\">):</span>\n    <span class=\"n\">system_check_removed_details</span> <span class=\"o\">=</span> <span class=\"p\">{</span>\n        <span class=\"s2\">&quot;msg&quot;</span><span class=\"p\">:</span> <span class=\"p\">(</span>\n            <span class=\"s2\">&quot;IPAddressField has been removed except for support in &quot;</span>\n            <span class=\"s2\">&quot;historical migrations.&quot;</span>\n        <span class=\"p\">),</span>\n        <span class=\"s2\">&quot;hint&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;Use GenericIPAddressField instead.&quot;</span><span class=\"p\">,</span>\n        <span class=\"s2\">&quot;id&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;fields.E900&quot;</span><span class=\"p\">,</span>  <span class=\"c1\"># pick a unique ID for your field.</span>\n    <span class=\"p\">}</span>\n</code></pre></div>\n<p>You should keep the field’s methods that are required for it to operate in\ndatabase migrations such as <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__()</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code>, and\n<code class=\"docutils literal notranslate\"><span class=\"pre\">get_internal_type()</span></code>. Keep this stub field for as long as any migrations\nwhich reference the field exist. For example, after squashing migrations and\nremoving the old ones, you should be able to remove the field completely.</p>\n</section>\n<section id=\"data-migrations\">\n<span id=\"id4\"></span><h2>Migracje Danych<a class=\"heading-anchor\" href=\"#data-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>As well as changing the database schema, you can also use migrations to change\nthe data in the database itself, in conjunction with the schema if you want.</p>\n<p>Migrations that alter data are usually called „data migrations”; they’re best\nwritten as separate migrations, sitting alongside your schema migrations.</p>\n<p>Django can’t automatically generate data migrations for you, as it does with\nschema migrations, but it’s not very hard to write them. Migration files in\nDjango are made up of <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/\"><span class=\"doc\">Operations</span></a>, and\nthe main operation you use for data migrations is\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a>.</p>\n<p>To start, make an empty migration file you can work from (Django will put\nthe file in the right place, suggest a name, and add dependencies for you):</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code>python<span class=\"w\"> </span>manage.py<span class=\"w\"> </span>makemigrations<span class=\"w\"> </span>--empty<span class=\"w\"> </span>yourappname\n</code></pre></div>\n<p>Then, open up the file; it should look something like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Generated by Django A.B on YYYY-MM-DD HH:MM</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">migrations</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"s2\">&quot;yourappname&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;0001_initial&quot;</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n</code></pre></div>\n<p>Now, all you need to do is create a new function and have\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> use it.\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> expects a callable as its argument\nwhich takes two arguments - the first is an <a class=\"reference internal\" href=\"/pl/5.2/ref/applications/\"><span class=\"doc\">app registry</span></a> that has the historical versions of all your models\nloaded into it to match where in your history the migration sits, and the\nsecond is a <a class=\"reference internal\" href=\"/pl/5.2/ref/schema-editor/\"><span class=\"doc\">SchemaEditor</span></a>, which you can use to\nmanually effect database schema changes (but beware, doing this can confuse\nthe migration autodetector!)</p>\n<p>Let’s write a migration that populates our new <code class=\"docutils literal notranslate\"><span class=\"pre\">name</span></code> field with the combined\nvalues of <code class=\"docutils literal notranslate\"><span class=\"pre\">first_name</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">last_name</span></code> (we’ve come to our senses and\nrealized that not everyone has first and last names). All we need to do is use\nthe historical model and iterate over the rows:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">migrations</span>\n\n\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">combine_names</span><span class=\"p\">(</span><span class=\"n\">apps</span><span class=\"p\">,</span> <span class=\"n\">schema_editor</span><span class=\"p\">):</span>\n    <span class=\"c1\"># We can&#39;t import the Person model directly as it may be a newer</span>\n    <span class=\"c1\"># version than this migration expects. We use the historical version.</span>\n    <span class=\"n\">Person</span> <span class=\"o\">=</span> <span class=\"n\">apps</span><span class=\"o\">.</span><span class=\"n\">get_model</span><span class=\"p\">(</span><span class=\"s2\">&quot;yourappname&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;Person&quot;</span><span class=\"p\">)</span>\n    <span class=\"k\">for</span> <span class=\"n\">person</span> <span class=\"ow\">in</span> <span class=\"n\">Person</span><span class=\"o\">.</span><span class=\"n\">objects</span><span class=\"o\">.</span><span class=\"n\">all</span><span class=\"p\">():</span>\n        <span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"sa\">f</span><span class=\"s2\">&quot;</span><span class=\"si\">{</span><span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">first_name</span><span class=\"si\">}</span><span class=\"s2\"> </span><span class=\"si\">{</span><span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">last_name</span><span class=\"si\">}</span><span class=\"s2\">&quot;</span>\n        <span class=\"n\">person</span><span class=\"o\">.</span><span class=\"n\">save</span><span class=\"p\">()</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"s2\">&quot;yourappname&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;0001_initial&quot;</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">RunPython</span><span class=\"p\">(</span><span class=\"n\">combine_names</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n<p>Once that’s done, we can run <code class=\"docutils literal notranslate\"><span class=\"pre\">python</span> <span class=\"pre\">manage.py</span> <span class=\"pre\">migrate</span></code> as normal and the\ndata migration will run in place alongside other migrations.</p>\n<p>You can pass a second callable to\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> to run whatever logic you\nwant executed when migrating backwards. If this callable is omitted, migrating\nbackwards will raise an exception.</p>\n<section id=\"accessing-models-from-other-apps\">\n<h3>Accessing models from other apps<a class=\"heading-anchor\" href=\"#accessing-models-from-other-apps\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When writing a <code class=\"docutils literal notranslate\"><span class=\"pre\">RunPython</span></code> function that uses models from apps other than the\none in which the migration is located, the migration’s <code class=\"docutils literal notranslate\"><span class=\"pre\">dependencies</span></code>\nattribute should include the latest migration of each app that is involved,\notherwise you may get an error similar to: <code class=\"docutils literal notranslate\"><span class=\"pre\">LookupError:</span> <span class=\"pre\">No</span> <span class=\"pre\">installed</span> <span class=\"pre\">app</span>\n<span class=\"pre\">with</span> <span class=\"pre\">label</span> <span class=\"pre\">'myappname'</span></code> when you try to retrieve the model in the <code class=\"docutils literal notranslate\"><span class=\"pre\">RunPython</span></code>\nfunction using <code class=\"docutils literal notranslate\"><span class=\"pre\">apps.get_model()</span></code>.</p>\n<p>In the following example, we have a migration in <code class=\"docutils literal notranslate\"><span class=\"pre\">app1</span></code> which needs to use\nmodels in <code class=\"docutils literal notranslate\"><span class=\"pre\">app2</span></code>. We aren’t concerned with the details of <code class=\"docutils literal notranslate\"><span class=\"pre\">move_m1</span></code> other\nthan the fact it will need to access models from both apps. Therefore we’ve\nadded a dependency that specifies the last migration of <code class=\"docutils literal notranslate\"><span class=\"pre\">app2</span></code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Migration</span><span class=\"p\">(</span><span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">Migration</span><span class=\"p\">):</span>\n    <span class=\"n\">dependencies</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"s2\">&quot;app1&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;0001_initial&quot;</span><span class=\"p\">),</span>\n        <span class=\"c1\"># added dependency to enable using models from app2 in move_m1</span>\n        <span class=\"p\">(</span><span class=\"s2\">&quot;app2&quot;</span><span class=\"p\">,</span> <span class=\"s2\">&quot;0004_foobar&quot;</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n\n    <span class=\"n\">operations</span> <span class=\"o\">=</span> <span class=\"p\">[</span>\n        <span class=\"n\">migrations</span><span class=\"o\">.</span><span class=\"n\">RunPython</span><span class=\"p\">(</span><span class=\"n\">move_m1</span><span class=\"p\">),</span>\n    <span class=\"p\">]</span>\n</code></pre></div>\n</section>\n<section id=\"more-advanced-migrations\">\n<h3>Bardziej zaawansowane migracje<a class=\"heading-anchor\" href=\"#more-advanced-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If you’re interested in the more advanced migration operations, or want\nto be able to write your own, see the <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/\"><span class=\"doc\">migration operations reference</span></a> and the „how-to” on <a class=\"reference internal\" href=\"/pl/5.2/howto/writing-migrations/\"><span class=\"doc\">writing migrations</span></a>.</p>\n</section>\n</section>\n<section id=\"squashing-migrations\">\n<span id=\"migration-squashing\"></span><h2>Squashing migrations<a class=\"heading-anchor\" href=\"#squashing-migrations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>You are encouraged to make migrations freely and not worry about how many you\nhave; the migration code is optimized to deal with hundreds at a time without\nmuch slowdown. However, eventually you will want to move back from having\nseveral hundred migrations to just a few, and that’s where squashing comes in.</p>\n<p>Squashing is the act of reducing an existing set of many migrations down to\none (or sometimes a few) migrations which still represent the same changes.</p>\n<p>Django does this by taking all of your existing migrations, extracting their\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Operation</span></code>s and putting them all in sequence, and then running an optimizer\nover them to try and reduce the length of the list - for example, it knows\nthat <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.CreateModel\" title=\"django.db.migrations.operations.CreateModel\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">CreateModel</span></code></a> and\n<a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.DeleteModel\" title=\"django.db.migrations.operations.DeleteModel\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">DeleteModel</span></code></a> cancel each other out,\nand it knows that <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.AddField\" title=\"django.db.migrations.operations.AddField\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">AddField</span></code></a> can be\nrolled into <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.CreateModel\" title=\"django.db.migrations.operations.CreateModel\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">CreateModel</span></code></a>.</p>\n<p>Once the operation sequence has been reduced as much as possible - the amount\npossible depends on how closely intertwined your models are and if you have\nany <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunSQL\" title=\"django.db.migrations.operations.RunSQL\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunSQL</span></code></a>\nor <a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/#django.db.migrations.operations.RunPython\" title=\"django.db.migrations.operations.RunPython\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RunPython</span></code></a> operations (which can’t\nbe optimized through unless they are marked as <code class=\"docutils literal notranslate\"><span class=\"pre\">elidable</span></code>) - Django will then\nwrite it back out into a new set of migration files.</p>\n<p>These files are marked to say they replace the previously-squashed migrations,\nso they can coexist with the old migration files, and Django will intelligently\nswitch between them depending where you are in the history. If you’re still\npart-way through the set of migrations that you squashed, it will keep using\nthem until it hits the end and then switch to the squashed history, while new\ninstalls will use the new squashed migration and skip all the old ones.</p>\n<p>This enables you to squash and not mess up systems currently in production\nthat aren’t fully up-to-date yet. The recommended process is to squash, keeping\nthe old files, commit and release, wait until all systems are upgraded with\nthe new release (or if you’re a third-party project, ensure your users upgrade\nreleases in order without skipping any), and then remove the old files, commit\nand do a second release.</p>\n<p>The command that backs all this is <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-squashmigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">squashmigrations</span></code></a> - pass it the\napp label and migration name you want to squash up to, and it’ll get to work:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code>$<span class=\"w\"> </span>./manage.py<span class=\"w\"> </span>squashmigrations<span class=\"w\"> </span>myapp<span class=\"w\"> </span><span class=\"m\">0004</span>\nWill<span class=\"w\"> </span>squash<span class=\"w\"> </span>the<span class=\"w\"> </span>following<span class=\"w\"> </span>migrations:\n<span class=\"w\"> </span>-<span class=\"w\"> </span>0001_initial\n<span class=\"w\"> </span>-<span class=\"w\"> </span>0002_some_change\n<span class=\"w\"> </span>-<span class=\"w\"> </span>0003_another_change\n<span class=\"w\"> </span>-<span class=\"w\"> </span>0004_undo_something\nDo<span class=\"w\"> </span>you<span class=\"w\"> </span>wish<span class=\"w\"> </span>to<span class=\"w\"> </span>proceed?<span class=\"w\"> </span><span class=\"o\">[</span>y/N<span class=\"o\">]</span><span class=\"w\"> </span>y\nOptimizing...\n<span class=\"w\">  </span>Optimized<span class=\"w\"> </span>from<span class=\"w\"> </span><span class=\"m\">12</span><span class=\"w\"> </span>operations<span class=\"w\"> </span>to<span class=\"w\"> </span><span class=\"m\">7</span><span class=\"w\"> </span>operations.\nCreated<span class=\"w\"> </span>new<span class=\"w\"> </span>squashed<span class=\"w\"> </span>migration<span class=\"w\"> </span>/home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_something.py\n<span class=\"w\">  </span>You<span class=\"w\"> </span>should<span class=\"w\"> </span>commit<span class=\"w\"> </span>this<span class=\"w\"> </span>migration<span class=\"w\"> </span>but<span class=\"w\"> </span>leave<span class=\"w\"> </span>the<span class=\"w\"> </span>old<span class=\"w\"> </span>ones<span class=\"w\"> </span><span class=\"k\">in</span><span class=\"w\"> </span>place<span class=\"p\">;</span>\n<span class=\"w\">  </span>the<span class=\"w\"> </span>new<span class=\"w\"> </span>migration<span class=\"w\"> </span>will<span class=\"w\"> </span>be<span class=\"w\"> </span>used<span class=\"w\"> </span><span class=\"k\">for</span><span class=\"w\"> </span>new<span class=\"w\"> </span>installs.<span class=\"w\"> </span>Once<span class=\"w\"> </span>you<span class=\"w\"> </span>are<span class=\"w\"> </span>sure\n<span class=\"w\">  </span>all<span class=\"w\"> </span>instances<span class=\"w\"> </span>of<span class=\"w\"> </span>the<span class=\"w\"> </span>codebase<span class=\"w\"> </span>have<span class=\"w\"> </span>applied<span class=\"w\"> </span>the<span class=\"w\"> </span>migrations<span class=\"w\"> </span>you<span class=\"w\"> </span>squashed,\n<span class=\"w\">  </span>you<span class=\"w\"> </span>can<span class=\"w\"> </span>delete<span class=\"w\"> </span>them.\n</code></pre></div>\n<p>Use the <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#cmdoption-squashmigrations-squashed-name\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">squashmigrations</span> <span class=\"pre\">--squashed-name</span></code></a> option if you want to set\nthe name of the squashed migration rather than use an autogenerated one.</p>\n<p>Note that model interdependencies in Django can get very complex, and squashing\nmay result in migrations that do not run; either mis-optimized (in which case\nyou can try again with <code class=\"docutils literal notranslate\"><span class=\"pre\">--no-optimize</span></code>, though you should also report an issue),\nor with a <code class=\"docutils literal notranslate\"><span class=\"pre\">CircularDependencyError</span></code>, in which case you can manually resolve it.</p>\n<p>To manually resolve a <code class=\"docutils literal notranslate\"><span class=\"pre\">CircularDependencyError</span></code>, break out one of\nthe ForeignKeys in the circular dependency loop into a separate\nmigration, and move the dependency on the other app with it. If you’re unsure,\nsee how <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> deals with the problem when asked to create\nbrand new migrations from your models. In a future release of Django,\n<a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-squashmigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">squashmigrations</span></code></a> will be updated to attempt to resolve these errors\nitself.</p>\n<p>Once you’ve squashed your migration, you should then commit it alongside the\nmigrations it replaces and distribute this change to all running instances\nof your application, making sure that they run <code class=\"docutils literal notranslate\"><span class=\"pre\">migrate</span></code> to store the change\nin their database.</p>\n<p>You must then transition the squashed migration to a normal migration by:</p>\n<ul class=\"simple\">\n<li><p>Deleting all the migration files it replaces.</p></li>\n<li><p>Updating all migrations that depend on the deleted migrations to depend on\nthe squashed migration instead.</p></li>\n<li><p>Removing the <code class=\"docutils literal notranslate\"><span class=\"pre\">replaces</span></code> attribute in the <code class=\"docutils literal notranslate\"><span class=\"pre\">Migration</span></code> class of the\nsquashed migration (this is how Django tells that it is a squashed migration).</p></li>\n</ul>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Informacja</p>\n<p>Once you’ve squashed a migration, you should not then re-squash that squashed\nmigration until you have fully transitioned it to a normal migration.</p>\n</aside>\n<aside class=\"admonition-pruning-references-to-deleted-migrations admonition\">\n<p class=\"admonition-title\">Pruning references to deleted migrations</p>\n<p>If it is likely that you may reuse the name of a deleted migration in the\nfuture, you should remove references to it from Django’s migrations table\nwith the <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#cmdoption-migrate-prune\"><code class=\"xref std std-option docutils literal notranslate\"><span class=\"pre\">migrate</span> <span class=\"pre\">--prune</span></code></a> option.</p>\n</aside>\n</section>\n<section id=\"serializing-values\">\n<span id=\"migration-serializing\"></span><h2>Serializing values<a class=\"heading-anchor\" href=\"#serializing-values\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Migrations are Python files containing the old definitions of your models\n- thus, to write them, Django must take the current state of your models and\nserialize them out into a file.</p>\n<p>While Django can serialize most things, there are some things that we just\ncan’t serialize out into a valid Python representation - there’s no Python\nstandard for how a value can be turned back into code (<code class=\"docutils literal notranslate\"><span class=\"pre\">repr()</span></code> only works\nfor basic values, and doesn’t specify import paths).</p>\n<p>Django can serialize the following:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">int</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">float</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">bool</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">str</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">bytes</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">None</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">NoneType</span></code></p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">list</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">set</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">tuple</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">dict</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">range</span></code>.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.date</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.time</span></code>, and <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.datetime</span></code> instances\n(include those that are timezone-aware)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">decimal.Decimal</span></code> instances</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">enum.Enum</span></code>  and <code class=\"docutils literal notranslate\"><span class=\"pre\">enum.Flag</span></code> instances</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">uuid.UUID</span></code> instances</p></li>\n<li><p><a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.partial\" title=\"(w Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">functools.partial()</span></code></a> and <a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.partialmethod\" title=\"(w Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">functools.partialmethod</span></code></a> instances\nwhich have serializable <code class=\"docutils literal notranslate\"><span class=\"pre\">func</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">args</span></code>, and <code class=\"docutils literal notranslate\"><span class=\"pre\">keywords</span></code> values.</p></li>\n<li><p>Pure and concrete path objects from <a class=\"reference external\" href=\"https://docs.python.org/3/library/pathlib.html#module-pathlib\" title=\"(w Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\"><span class=\"pre\">pathlib</span></code></a>. Concrete paths are\nconverted to their pure path equivalent, e.g. <a class=\"reference external\" href=\"https://docs.python.org/3/library/pathlib.html#pathlib.PosixPath\" title=\"(w Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">pathlib.PosixPath</span></code></a> to\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/pathlib.html#pathlib.PurePosixPath\" title=\"(w Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">pathlib.PurePosixPath</span></code></a>.</p></li>\n<li><p><a class=\"reference external\" href=\"https://docs.python.org/3/library/os.html#os.PathLike\" title=\"(w Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">os.PathLike</span></code></a> instances, e.g. <a class=\"reference external\" href=\"https://docs.python.org/3/library/os.html#os.DirEntry\" title=\"(w Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">os.DirEntry</span></code></a>, which are\nconverted to <code class=\"docutils literal notranslate\"><span class=\"pre\">str</span></code> or <code class=\"docutils literal notranslate\"><span class=\"pre\">bytes</span></code> using <a class=\"reference external\" href=\"https://docs.python.org/3/library/os.html#os.fspath\" title=\"(w Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">os.fspath()</span></code></a>.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">LazyObject</span></code> instances which wrap a serializable value.</p></li>\n<li><p>Enumeration types (e.g. <code class=\"docutils literal notranslate\"><span class=\"pre\">TextChoices</span></code> or <code class=\"docutils literal notranslate\"><span class=\"pre\">IntegerChoices</span></code>) instances.</p></li>\n<li><p>Any Django field</p></li>\n<li><p>Any function or method reference (e.g. <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime.datetime.today</span></code>) (must be\nin module’s top-level scope)</p>\n<ul>\n<li><p>Functions may be decorated if wrapped properly, i.e. using\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.wraps\" title=\"(w Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">functools.wraps()</span></code></a></p></li>\n<li><p>The <a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.cache\" title=\"(w Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">functools.cache()</span></code></a> and <a class=\"reference external\" href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" title=\"(w Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">functools.lru_cache()</span></code></a> decorators are\nexplicitly supported</p></li>\n</ul>\n</li>\n<li><p>Unbound methods used from within the class body</p></li>\n<li><p>Any class reference (must be in module’s top-level scope)</p></li>\n<li><p>Anything with a custom <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> method (<a class=\"reference internal\" href=\"#custom-deconstruct-method\"><span class=\"std std-ref\">see below</span></a>)</p></li>\n</ul>\n<p>Django cannot serialize:</p>\n<ul class=\"simple\">\n<li><p>Klasy zagnieżdzone</p></li>\n<li><p>Arbitrary class instances (e.g. <code class=\"docutils literal notranslate\"><span class=\"pre\">MyClass(4.3,</span> <span class=\"pre\">5.7)</span></code>)</p></li>\n<li><p>Lambdas</p></li>\n</ul>\n<section id=\"custom-serializers\">\n<span id=\"custom-migration-serializers\"></span><h3>Custom serializers<a class=\"heading-anchor\" href=\"#custom-serializers\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You can serialize other types by writing a custom serializer. For example, if\nDjango didn’t serialize <a class=\"reference external\" href=\"https://docs.python.org/3/library/decimal.html#decimal.Decimal\" title=\"(w Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Decimal</span></code></a> by default, you could do\nthis:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">decimal</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">Decimal</span>\n\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db.migrations.serializer</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">BaseSerializer</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db.migrations.writer</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">MigrationWriter</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">DecimalSerializer</span><span class=\"p\">(</span><span class=\"n\">BaseSerializer</span><span class=\"p\">):</span>\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">serialize</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"nb\">repr</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">value</span><span class=\"p\">),</span> <span class=\"p\">{</span><span class=\"s2\">&quot;from decimal import Decimal&quot;</span><span class=\"p\">}</span>\n\n\n<span class=\"n\">MigrationWriter</span><span class=\"o\">.</span><span class=\"n\">register_serializer</span><span class=\"p\">(</span><span class=\"n\">Decimal</span><span class=\"p\">,</span> <span class=\"n\">DecimalSerializer</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>The first argument of <code class=\"docutils literal notranslate\"><span class=\"pre\">MigrationWriter.register_serializer()</span></code> is a type or\niterable of types that should use the serializer.</p>\n<p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">serialize()</span></code> method of your serializer must return a string of how the\nvalue should appear in migrations and a set of any imports that are needed in\nthe migration.</p>\n</section>\n<section id=\"adding-a-deconstruct-method\">\n<span id=\"custom-deconstruct-method\"></span><h3>Adding a <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> method<a class=\"heading-anchor\" href=\"#adding-a-deconstruct-method\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You can let Django serialize your own custom class instances by giving the class\na <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> method. It takes no arguments, and should return a tuple\nof three things <code class=\"docutils literal notranslate\"><span class=\"pre\">(path,</span> <span class=\"pre\">args,</span> <span class=\"pre\">kwargs)</span></code>:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">path</span></code> should be the Python path to the class, with the class name included\nas the last part (for example, <code class=\"docutils literal notranslate\"><span class=\"pre\">myapp.custom_things.MyClass</span></code>). If your\nclass is not available at the top level of a module it is not serializable.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">args</span></code> should be a list of positional arguments to pass to your class»\n<code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span></code> method. Everything in this list should itself be serializable.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">kwargs</span></code> should be a dict of keyword arguments to pass to your class»\n<code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span></code> method. Every value should itself be serializable.</p></li>\n</ul>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Informacja</p>\n<p>This return value is different from the <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> method\n<a class=\"reference internal\" href=\"/pl/5.2/howto/custom-model-fields/#custom-field-deconstruct-method\"><span class=\"std std-ref\">for custom fields</span></a> which returns a\ntuple of four items.</p>\n</aside>\n<p>Django will write out the value as an instantiation of your class with the\ngiven arguments, similar to the way it writes out references to Django fields.</p>\n<p>To prevent a new migration from being created each time\n<a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> is run, you should also add a <code class=\"docutils literal notranslate\"><span class=\"pre\">__eq__()</span></code> method to\nthe decorated class. This function will be called by Django’s migration\nframework to detect changes between states.</p>\n<p>As long as all of the arguments to your class» constructor are themselves\nserializable, you can use the <code class=\"docutils literal notranslate\"><span class=\"pre\">&#64;deconstructible</span></code> class decorator from\n<code class=\"docutils literal notranslate\"><span class=\"pre\">django.utils.deconstruct</span></code> to add the <code class=\"docutils literal notranslate\"><span class=\"pre\">deconstruct()</span></code> method:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.utils.deconstruct</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">deconstructible</span>\n\n\n<span class=\"nd\">@deconstructible</span>\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">MyCustomClass</span><span class=\"p\">:</span>\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">foo</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">foo</span> <span class=\"o\">=</span> <span class=\"n\">foo</span>\n        <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"fm\">__eq__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">other</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">foo</span> <span class=\"o\">==</span> <span class=\"n\">other</span><span class=\"o\">.</span><span class=\"n\">foo</span>\n</code></pre></div>\n<p>The decorator adds logic to capture and preserve the arguments on their\nway into your constructor, and then returns those arguments exactly when\ndeconstruct() is called.</p>\n</section>\n</section>\n<section id=\"supporting-multiple-django-versions\">\n<h2>Supporting multiple Django versions<a class=\"heading-anchor\" href=\"#supporting-multiple-django-versions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>If you are the maintainer of a third-party app with models, you may need to\nship migrations that support multiple Django versions. In this case, you should\nalways run <a class=\"reference internal\" href=\"/pl/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">makemigrations</span></code></a> <strong>with the lowest Django version you wish\nto support</strong>.</p>\n<p>The migrations system will maintain backwards-compatibility according to the\nsame policy as the rest of Django, so migration files generated on Django X.Y\nshould run unchanged on Django X.Y+1. The migrations system does not promise\nforwards-compatibility, however. New features may be added, and migration files\ngenerated with newer versions of Django may not work on older versions.</p>\n<aside class=\"admonition admonition-seealso\">\n<p class=\"admonition-title\">Zobacz także</p>\n<dl class=\"simple\">\n<dt><a class=\"reference internal\" href=\"/pl/5.2/ref/migration-operations/\"><span class=\"doc\">The Migrations Operations Reference</span></a></dt><dd><p>Covers the schema operations API, special operations, and writing your\nown operations.</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/pl/5.2/howto/writing-migrations/\"><span class=\"doc\">The Writing Migrations „how-to”</span></a></dt><dd><p>Explains how to structure and write database migrations for different\nscenarios you might encounter.</p>\n</dd>\n</dl>\n</aside>\n</section>","rootId":"module-django.db.migrations","toc":[{"title":"The Commands","anchor":"the-commands","children":[]},{"title":"Backend Support","anchor":"backend-support","children":[{"title":"PostgreSQL","anchor":"postgresql","children":[]},{"title":"MySQL","anchor":"mysql","children":[]},{"title":"SQLite","anchor":"sqlite","children":[]}]},{"title":"Workflow","anchor":"workflow","children":[{"title":"Kontrola wersji","anchor":"version-control","children":[]}]},{"title":"Transactions","anchor":"transactions","children":[]},{"title":"Zależności","anchor":"dependencies","children":[{"title":"Swappable dependencies","anchor":"swappable-dependencies","children":[]}]},{"title":"Pliki migracji","anchor":"migration-files","children":[{"title":"Custom fields","anchor":"custom-fields","children":[]},{"title":"Zarządcy modeli","anchor":"model-managers","children":[]},{"title":"Initial migrations","anchor":"initial-migrations","children":[]},{"title":"History consistency","anchor":"history-consistency","children":[]}]},{"title":"Dodawanie migracji do aplikacji","anchor":"adding-migrations-to-apps","children":[]},{"title":"Reversing migrations","anchor":"reversing-migrations","children":[]},{"title":"Modele historyczne","anchor":"historical-models","children":[]},{"title":"Considerations when removing model fields","anchor":"considerations-when-removing-model-fields","children":[]},{"title":"Migracje Danych","anchor":"data-migrations","children":[{"title":"Accessing models from other apps","anchor":"accessing-models-from-other-apps","children":[]},{"title":"Bardziej zaawansowane migracje","anchor":"more-advanced-migrations","children":[]}]},{"title":"Squashing migrations","anchor":"squashing-migrations","children":[]},{"title":"Serializing values","anchor":"serializing-values","children":[{"title":"Custom serializers","anchor":"custom-serializers","children":[]},{"title":"Adding a deconstruct() method","anchor":"adding-a-deconstruct-method","children":[]}]},{"title":"Supporting multiple Django versions","anchor":"supporting-multiple-django-versions","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Używanie Django","url":"/pl/5.2/topics/"}],"prev":{"docname":"topics/class-based-views/mixins","title":"Using mixins with class-based views","url":"/pl/5.2/topics/class-based-views/mixins/"},"next":{"docname":"topics/files","title":"Managing files","url":"/pl/5.2/topics/files/"},"formats":{"html":"/pl/5.2/topics/migrations/","markdown":"/pl/5.2/topics/migrations.md","json":"/pl/5.2/topics/migrations.json"},"source":"https://github.com/django/django/blob/stable/5.2.x/docs/topics/migrations.txt","official":"https://docs.djangoproject.com/pl/5.2/topics/migrations/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10"],"inLocales":["en","sv","zh-hans","ga","fr","ja","id","it","pt-br","ko","es","el","pl"]}