<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title>Jean-Michel Plourde's Website</title>
	<link href="https://jmplourde.com/atom.xml" rel="self" />
	<updated>2023-08-24T15:16:58Z</updated>
	<author>
		<name>jmplourde</name>
	</author>
	<id>https://jmplourde.com,2023-01-08:default-atom-feed/</id>
	<entry>
		<title>TIL: Running Python code as a migration operation in Django</title>
		<content type="html">&lt;h1&gt;TIL: Running Python code as a migration operation in Django&lt;/h1&gt;
&lt;p&gt;2023-08-21&lt;/p&gt;
&lt;p&gt;When I started learning Django, I was confused with the difference between &lt;code&gt;makemigrations&lt;/code&gt; and &lt;code&gt;migrate&lt;/code&gt; commands. I got it after a while, but I never truly had to work with complex migrations or write custome ones. I recently had to write a custom migration to change a &lt;code&gt;ForeignKey&lt;/code&gt; field to a &lt;code&gt;OneToOneField&lt;/code&gt; and I used the &lt;a href=&quot;https://docs.djangoproject.com/en/4.2/ref/migration-operations/#runsql&quot;&gt;RunSQL&lt;/a&gt; special operation which allows to run raw sql queries. It allowed me to better understand migrations and gave me the confidence to push my changes in production.&lt;/p&gt;
&lt;p&gt;Now I wanted to refactor an unnecessary many-to-many model into a one-to-one field in another model. The models looked like the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from accounts import models as account_models


# the model I want to get rid of
class HomeAddress(BaseModel):
    home = models.ForeignKey(Home, on_delete=models.CASCADE)
    address = models.ForeignKey(
        account_models.Address,
        on_delete=models.CASCADE,
    )
    class Meta:
        verbose_name_plural = &amp;quot;home addresses&amp;quot;


class Home(BaseModel):
    name = models.CharField(max_length=50, default=&amp;quot;Home&amp;quot;)
    address = models.OneToOneField(  # the field I want to replace the model with
        account_models.Address,
        on_delete=models.PROTECT,
    )

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The challenge was to copy the &lt;code&gt;Address&lt;/code&gt; refered in each &lt;code&gt;HomeAddress&lt;/code&gt; row to the refered &lt;code&gt;Home&lt;/code&gt;. I wasn&#39;t sure how I would solve this and dreaded the raw SQL query, not wanting to mess up the production data. I asked ChatGPT for some inspiration and it suggested using the &lt;a href=&quot;https://docs.djangoproject.com/en/4.2/ref/migration-operations/#runpython&quot;&gt;RunPython&lt;/a&gt; special operation. You first declare a function that takes two arguments; the first being the name of the app containing the historical models that matches the operation and the second is an instance of &lt;a href=&quot;https://docs.djangoproject.com/en/4.2/ref/schema-editor/#django.db.backends.base.schema.BaseDatabaseSchemaEditor&quot;&gt;SchemaEditor&lt;/a&gt; the class that turns operations into SQL. The function code describes the changes that will be applied.&lt;/p&gt;
&lt;p&gt;A second function is declared that accepts the same two arguments and its code should undo what has been done by the first function. This makes the migration reversible otherwise the changes are permanent. The two functions are passed to the &lt;code&gt;RunPython&lt;/code&gt; function called inside the &lt;code&gt;operations&lt;/code&gt; list of the &lt;code&gt;Migration&lt;/code&gt; class. For database backends that do not support &lt;a href=&quot;https://en.wikipedia.org/wiki/Data_definition_language&quot;&gt;Data Definition Language (DDL)&lt;/a&gt; transactions (&lt;code&gt;CREATE&lt;/code&gt;, &lt;code&gt;ALTER&lt;/code&gt;, etc.), &lt;code&gt;RunPython&lt;/code&gt; will run its content inside a transaction.&lt;/p&gt;
&lt;p&gt;For databases that do support DDL like PostgreSQL, no other transactions are added besides the one generated by a migration. A migration with both schema changes and &lt;code&gt;RunPython&lt;/code&gt; operation will raise an exception stating the changes cannot be applied because it has pending trigger events.&lt;/p&gt;
&lt;p&gt;What I ended up doing is generating a migration to add the &lt;code&gt;Home.address&lt;/code&gt; field, then generated an empty migration and wrote the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from django.db import migrations

from accounts import models as account_models


def replace_home_with_address(apps, schema_editor):
    home_address_model = apps.get_model(&#39;my_app&#39;, &#39;HomeAddress&#39;)

    for home_address in home_address_model.objects.all():
        address = home_address.address
        address = account_models.Address.objects.create(
	    address_line_1=f&amp;quot;123 Fake Street&amp;quot;,
	    address_line_2=&amp;quot;Building 1&amp;quot;,
	    city=&amp;quot;Test City&amp;quot;,
	    zip_code=&amp;quot;12345&amp;quot;,
	    country_id=home_address.address.country.id,
	    subdivision_id=home_address.address.subdivision.id,
        )
        home_address.home.address_id = address.id
        home_address.home.save()


class Migration(migrations.Migration):

    dependencies = [
        (&#39;my_app&#39;, &#39;0002_auto_20230821_1308&#39;),
    ]

    operations = [
        migrations.RunPython(replace_home_with_address),
    ]

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So here, I loop over the &lt;code&gt;HomeAddress&lt;/code&gt; rows and for each one of them, I put the &lt;code&gt;HomeAddress.address&lt;/code&gt; reference into &lt;code&gt;HomeAddress.home.address&lt;/code&gt; and save. Note that for readability purpose, I didn&#39;t include the query prefetching code.&lt;/p&gt;</content>
		<link href="https://jmplourde.com/til-django-run-python-migration-operation"/>
		<id>https://jmplourde.com/til-django-run-python-migration-operation</id>
		<updated>2023-08-21T00:00:00Z</updated>
		<published>2023-08-21T00:00:00Z</published>
	</entry>
</feed>
