<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ayman Fekri on Medium]]></title>
        <description><![CDATA[Stories by Ayman Fekri on Medium]]></description>
        <link>https://medium.com/@aymanfekri?source=rss-30199a5c95f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9ipRyfYGaK6ZZi_c.</url>
            <title>Stories by Ayman Fekri on Medium</title>
            <link>https://medium.com/@aymanfekri?source=rss-30199a5c95f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:01:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aymanfekri/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The NULL Trap: Why Your Unique Constraints Are Failing (And How to Fix It)]]></title>
            <link>https://medium.com/@aymanfekri/the-null-trap-why-your-unique-constraints-are-failing-and-how-to-fix-it-350507589bb1?source=rss-30199a5c95f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/350507589bb1</guid>
            <dc:creator><![CDATA[Ayman Fekri]]></dc:creator>
            <pubDate>Thu, 14 May 2026 15:40:04 GMT</pubDate>
            <atom:updated>2026-05-14T15:40:04.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uk7Gb2vzWK9C6agA-sNYkg.png" /></figure><p>Recently, a fellow engineer<strong> </strong>encountered a frustrating database quirk while working with Laravel’s soft deletes.</p><p>When you use Laravel’s standard soft delete feature, it automatically adds a nullable deleted_at timestamp column to your table to mark records as deleted rather than permanently removing them. We needed to ensure that active users had unique email addresses, so we naturally tried to combine a unique constraint with this soft delete column. However, this seemingly straightforward approach completely failed to prevent duplicate active accounts.</p><p>Here is a breakdown of why this issue occurs — especially when relying on default soft delete implementations like Laravel’s — and a robust, elegant solution to fix it directly at the database level.</p><h3>The Issue: The NULL != NULL Dilemma</h3><p>Imagine you want to ensure that active users cannot register with an email address that is already in use. A common first instinct is to create a composite UNIQUE key using both the email and the deleted_at columns.</p><p>Your table structure might look something like this:</p><pre>CREATE TABLE bad_users (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    email VARCHAR(255) NOT NULL,<br>    deleted_at DATETIME NULL,    <br>    UNIQUE KEY (email, deleted_at)<br>) ENGINE=InnoDB;</pre><p>At first glance, this seems logical. However, if you try to insert multiple active users with the same email, the database will unexpectedly allow it:</p><pre>INSERT INTO bad_users (email, deleted_at) VALUES (&#39;user@test.com&#39;, NULL);<br>-- The following inserts SHOULD fail, but they succeed:<br>INSERT INTO bad_users (email, deleted_at) VALUES (&#39;user@test.com&#39;, NULL);<br>INSERT INTO bad_users (email, deleted_at) VALUES (&#39;user@test.com&#39;, NULL);</pre><p><strong>Why does this happen?</strong></p><p>In SQL, there is a fundamental rule regarding NULL values: <strong>NULL is never equal to </strong><strong>NULL</strong>. Because NULL represents an &quot;unknown&quot; value, the database engine treats every NULL in the deleted_at column as a distinct, unique value. Consequently, the unique constraint is effectively bypassed for any row where deleted_at is NULL.</p><h3>The Solution: Generated Virtual Columns</h3><p>One potential fix is to use a default date (like 1000-01-01) instead of NULL for active records. However, this is often impractical, semantically incorrect, and difficult to integrate into existing codebases.</p><p>A much cleaner approach relies on <strong>Generated Columns</strong>, allowing us to create a virtual, stored value specifically designed to handle the unique constraint correctly.</p><p>Here is the updated, working schema:</p><pre>CREATE TABLE users (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    email VARCHAR(255) NOT NULL,<br>    deleted_at DATETIME NULL,<br>    is_active TINYINT AS (IF(deleted_at IS NULL, 1, NULL)) STORED,<br>    UNIQUE KEY (email, is_active)<br>) ENGINE=InnoDB;</pre><p><strong>How it works:</strong></p><ul><li>We introduce a new stored generated column called is_active.</li><li>If deleted_at is NULL (meaning the user is active), is_active evaluates to 1.</li><li>If deleted_at has a timestamp (meaning the user is deleted), is_active evaluates to NULL.</li><li>The UNIQUE KEY is now placed on (email, is_active).</li></ul><p>Because active users will always have is_active = 1, the unique constraint will correctly trigger a duplicate key error if you try to insert the same email twice. Conversely, because soft-deleted users will have is_active = NULL, you can keep a historical record of multiple deleted accounts with the same email!</p><blockquote><em>💡 </em><strong><em>Universal Application: This Works for Any Framework</em></strong></blockquote><blockquote><em>Because this solution enforces data integrity directly at the </em><strong><em>database layer</em></strong><em>, it is entirely framework-agnostic. Whether you are using </em><strong><em>Laravel (PHP), Django (Python), Ruby on Rails, Spring Boot (Java), or Node.js with Prisma/Sequelize</em></strong><em>, this SQL architecture guarantees your database will never accept duplicate active emails, regardless of how your application’s ORM or validation logic is configured.</em></blockquote><h3>Implementation Example: Laravel Migrations</h3><p>If you are using a framework like Laravel, it is highly recommended to implement this generated column using raw SQL statements within your migration. While Laravel’s Schema Builder has convenience methods for virtual columns, raw SQL provides absolute precision and avoids version-specific formatting quirks.</p><p>Here is how you can write a bulletproof migration:</p><pre>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br>use Illuminate\Support\Facades\DB;<br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        // 1. Add the generated column using raw SQL for exact precision<br>        DB::statement(<br>            &#39;ALTER TABLE users ADD COLUMN is_active TINYINT GENERATED ALWAYS AS &#39;<br>            . &#39;(CASE WHEN deleted_at IS NULL THEN 1 ELSE NULL END) STORED&#39;<br>        );     // 2. Apply the unique constraint using the Schema Builder<br>        Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>            $table-&gt;unique([&#39;email&#39;, &#39;is_active&#39;]);<br>        });<br>    }    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::table(&#39;users&#39;, function (Blueprint $table) {<br>            // Always drop the index before dropping the column<br>            $table-&gt;dropUnique([&#39;email&#39;, &#39;is_active&#39;]);<br>            $table-&gt;dropColumn(&#39;is_active&#39;);<br>        });<br>    }<br>};</pre><p>By leveraging database-level generated columns, you maintain the semantic accuracy of NULL for your soft delete timestamps while ensuring absolute data integrity across your entire application.</p><p><em>Disclaimer: This article was edited and formatted with support from AI-based tools.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350507589bb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local S3 Storage Using MinIO and Podman]]></title>
            <link>https://medium.com/@aymanfekri/local-s3-storage-using-minio-and-podman-9e1a7c24e73d?source=rss-30199a5c95f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e1a7c24e73d</guid>
            <category><![CDATA[minio]]></category>
            <category><![CDATA[podman]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Ayman Fekri]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 20:58:50 GMT</pubDate>
            <atom:updated>2025-12-05T20:58:50.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7j0Y3L6EgGAT3q432ofXkw.jpeg" /></figure><p>Many of us have needed at some point to connect an application to cloud storage -especially an S3 — compatible service. The usual path involves creating a cloud account, dealing with access keys, and of course having an active internet connection. Most of these services are paid, and even the free tiers can be limiting.</p><p>If you want a <strong>quick, lightweight, and fully local alternative</strong>, especially when you already use containers manually, running MinIO through Podman is an excellent fit. It gives you a clean S3 environment right on your machine without installing extra binaries or depending on external services.</p><h3>1. Install MinIO ( high-performance, S3-compatible object storage solutio)</h3><p>We will run MinIO using a named volume (minio_data) so that your buckets and files persist even if you restart the container.</p><p>Bash</p><pre>podman run -d \<br>  --name minio \<br>  -p 9000:9000 \<br>  -p 9001:9001 \<br>  -e MINIO_ROOT_USER=admin \<br>  -e MINIO_ROOT_PASSWORD=strongpassword \<br>  -v minio_data:/data \<br>  quay.io/minio/minio server /data --console-address &quot;:9001&quot;</pre><p><strong>Port 9000:</strong> API access (used by your code/scripts).</p><p><strong>Port 9001:</strong> Browser Console UI.</p><h3>2. Configure the Client (mc) without Installation</h3><p>To keep your host machine clean, we will not install the mc binary. Instead, we will run it inside a container using an alias.</p><p>Step A: Prepare the configuration directory</p><p>Create a folder on your host to store your credentials to prevent permission issues.</p><p>Bash</p><pre>mkdir -p ~/.mc</pre><p>Step B: Create the Alias</p><p>This shortcut runs mc inside Podman but mounts your config folder so sessions are saved.</p><pre>alias mc=&#39;podman run -it --rm --network host -v ${HOME}/.mc:/root/.mc quay.io/minio/mc&#39;</pre><p>Step C: Connect to the Server</p><p>Authenticate the client with your running server.</p><pre># Syntax: mc alias set &lt;ALIAS_NAME&gt; &lt;URL&gt; &lt;ROOT_USER&gt; &lt;PASSWORD&gt;<br>mc alias set local-minio http://localhost:9000 admin strongpassword</pre><h3>3. Create Resources (Bucket &amp; User)</h3><p>First, create a bucket for your application:</p><pre>mc mb local-minio/app-data</pre><h3>Why use the CLI for Users?</h3><blockquote><strong><em>Important Note:</em></strong><em> You might look for a “Users” tab in the browser console (localhost:9001) and find it missing. In recent updates to the </em><strong><em>MinIO Community Edition</em></strong><em>, the feature to create standard users via the UI has been removed.</em></blockquote><blockquote><em>Therefore, using the command line (</em><em>mc) is currently the </em><strong><em>only reliable way</em></strong><em> to create users and manage permissions in the open-source version.</em></blockquote><p>Create the user identity via the CLI:</p><pre>mc admin user add local-minio developer dev-password123</pre><h3>4. Secure the User (Policy)</h3><p>By default, the new user has no permissions. You have two options:</p><h3>Option A: The Quick Way (Built-in Policy)</h3><p>If you want the user to have full access to <strong>everything</strong> (all buckets), use the built-in readwrite policy.</p><pre>mc admin policy attach local-minio readwrite --user developer</pre><h3>Option B: The Secure Way (Custom Policy)</h3><p>If you want to restrict the user to <strong>only</strong> access the app-data bucket:</p><ul><li><strong>Create the policy file</strong> (developer-policy.json):</li></ul><pre>{   &quot;Version&quot;: &quot;2012-10-17&quot;,   &quot;Statement&quot;: [     {       &quot;Effect&quot;: &quot;Allow&quot;,       &quot;Action&quot;: [&quot;s3:*&quot;],       &quot;Resource&quot;: [&quot;arn:aws:s3:::app-data/*&quot;, &quot;arn:aws:s3:::app-data&quot;]     }   ] }</pre><ul><li><strong>Apply the policy</strong>:</li></ul><pre>mc admin policy create local-minio dev-access developer-policy.json<br>mc admin policy attach local-minio dev-access --user developer</pre><h3>5. Generate API Keys (Service Account)</h3><p>To use this user with tools like Terraform, Boto3 (Python), or the AWS CLI, you need a Service Account (Access Key &amp; Secret Key).</p><pre>mc admin user svcacct add local-minio developer</pre><p><strong>Output (Save these!):</strong></p><pre>Access Key: X7A8...<br>Secret Key: 9b2c...</pre><h3>6. Connect with AWS CLI (The Efficient Way)</h3><p>Finally, let’s configure the standard AWS CLI to talk to your local MinIO.</p><p>Step A: Configure Profile</p><p>Run this command and enter the Access Key and Secret Key from Step 5.</p><p>Bash</p><pre>aws configure --profile minio</pre><ul><li><strong>Region:</strong> us-east-1 (Default)</li><li><strong>Output:</strong> json</li></ul><p>Step B: Create the Convenience Alias</p><p>Since AWS CLI defaults to Amazon’s servers, you must always provide the endpoint. Let’s make an alias to save typing:</p><p>Bash</p><pre>alias minio-cli=&#39;aws --profile minio --endpoint-url http://localhost:9000&#39;</pre><p>Step C: Test the Setup</p><p>Now you can manage your local storage using standard AWS commands:</p><pre># List buckets<br>minio-cli s3 ls</pre><pre># Upload a test file<br>echo &quot;Hello Local Cloud&quot; &gt; test.txt<br>minio-cli s3 cp test.txt s3://app-data/</pre><p><em>Disclaimer: This article was edited and formatted with support from AI-based tools.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e1a7c24e73d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ZROK: A Secure and Private Alternative to ngrok]]></title>
            <link>https://medium.com/@aymanfekri/zrok-a-secure-and-private-alternative-to-ngrok-cbb850d7a20e?source=rss-30199a5c95f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb850d7a20e</guid>
            <dc:creator><![CDATA[Ayman Fekri]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 07:54:38 GMT</pubDate>
            <atom:updated>2024-10-22T07:54:38.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*tUhAQmOS73WNBumc.png" /><figcaption>credit : zrok.io</figcaption></figure><p>In the world of web development, exposing local servers to the internet is often necessary for testing, collaboration, or demonstrations. Secure tunneling tools like ngrok and zrok simplify this process, but they differ significantly in their approach to security and privacy.</p><p><strong>ngrok:</strong></p><ul><li><strong>The Industry Standard:</strong> ngrok is a well-established cloud-based service with a freemium model. It provides a user-friendly interface and a robust feature set.</li><li><strong>Cloud-centric:</strong> Relies on ngrok’s infrastructure to establish and manage tunnels, making it convenient but potentially less private.</li><li><strong>Features:</strong></li><li>HTTP/HTTPS tunneling</li><li>Custom subdomains for personalized URLs</li><li>Request inspection and replay for debugging</li><li>TCP tunneling for exposing other services</li><li>Reserved domains and addresses (paid plans)</li><li><strong>Example:</strong></li></ul><pre>ngrok http 8080</pre><ul><li>This command creates a public URL that forwards traffic to your local server on port 8080. You’ll need to download ngrok, install it, and authenticate with an authtoken from your ngrok dashboard first.</li></ul><p><strong>zrok:</strong></p><ul><li><strong>Open-Source and Flexible:</strong> zrok is a newer, open-source solution built on the OpenZiti zero-trust network overlay. It offers both a free cloud service (zrok.io) and the ability to self-host for maximum control.</li><li><strong>Zero Trust Security:</strong> Emphasizes secure, private access by leveraging OpenZiti’s principles. Resources are not directly exposed to the public internet.</li><li><strong>Features:</strong></li><li>HTTP/HTTPS tunneling</li><li><strong>Private sharing with fine-grained access control</strong> using share tokens</li><li>No requirement for public IPs or open inbound ports, simplifying setup and enhancing security</li><li>Self-hosting option for enhanced privacy and security</li><li><strong>Example:</strong></li></ul><pre>zrok http 3000</pre><ul><li>This command generates a zrok URL that you can share. To create a private tunnel accessible only to those with a share token, use:</li><li>Bash</li></ul><pre>zrok http 3000 --private</pre><p><strong>Key Differences:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12554dee5553624ddaedf8a8578855a3/href">https://medium.com/media/12554dee5553624ddaedf8a8578855a3/href</a></iframe><p><strong>Why zrok’s Private Sharing Matters:</strong></p><ul><li><strong>Enhanced Security:</strong> No public exposure means reduced risk of unauthorized access.</li><li><strong>Simplified Setup:</strong> No need for public IPs or complex firewall configurations.</li><li><strong>Granular Control:</strong> Share resources only with those who have the unique share token.</li><li><strong>Improved Privacy:</strong> Data travels through the secure OpenZiti network, adding an extra layer of protection.</li></ul><p><strong>Choosing the Right Tool:</strong></p><ul><li><strong>Ease of Use:</strong> ngrok offers a simpler setup, especially for basic use cases.</li><li><strong>Privacy and Security:</strong> zrok’s zero-trust approach and self-hosting option provide greater control and privacy.</li><li><strong>Cost:</strong> Both offer free tiers, but ngrok’s advanced features require paid plans.</li><li><strong>Open Source Preference:</strong> zrok is the go-to choice for those who value open-source solutions.</li></ul><p><strong>Conclusion:</strong></p><p>Both ngrok and zrok are valuable tools for developers. ngrok offers a user-friendly experience and a mature feature set, while zrok prioritizes flexibility, privacy, and control through its open-source nature and zero-trust architecture. Choose the tool that best aligns with your specific needs and priorities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb850d7a20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Django App with UUIDs]]></title>
            <link>https://medium.com/@aymanfekri/supercharge-your-django-app-with-uuids-b97eeb7cc5c6?source=rss-30199a5c95f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97eeb7cc5c6</guid>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ayman Fekri]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 17:40:14 GMT</pubDate>
            <atom:updated>2024-10-11T17:40:14.584Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9qCBt7Y95YCDYt-TXY7QA.jpeg" /><figcaption><em>AI image created using Imagen 3 (Google).</em></figcaption></figure><p>In Django development, assigning unique identifiers to model instances is crucial for data management. While auto-incrementing integer primary keys are common, they can present limitations in distributed systems or when merging data from multiple sources. This is where UUIDs (Universally Unique Identifiers) come in.</p><h3>What is a UUID?</h3><p>A UUID is a 128-bit number that is, for all practical purposes, unique. It’s generated using a combination of factors, including timestamp, MAC address, and random numbers, ensuring a very low probability of collision even across different systems. This makes UUIDs ideal for:</p><ul><li><strong>Distributed Databases:</strong> Maintaining unique identifiers across multiple databases without coordination.</li><li><strong>Public APIs:</strong> Exposing identifiers without revealing internal database structure or sensitive information.</li><li><strong>Data Migrations:</strong> Preventing conflicts when merging data from different sources.</li></ul><h3>Why Use Both UUIDs and Integer Primary Keys?</h3><p>While UUIDs offer numerous benefits, they can sometimes be less efficient than integer primary keys for database operations, particularly when joining tables. This is because UUIDs are typically stored as 128-bit values, while integers are smaller and often indexed more efficiently.</p><p>A dual-identifier approach leverages the strengths of both:</p><ul><li><strong>Integer Primary Key:</strong> Provides efficient indexing and database performance for internal operations.</li><li><strong>UUID:</strong> Offers global uniqueness, security, and flexibility for external APIs and data management.</li></ul><h3>Implementing UUIDs in Django</h3><p>Here’s how you can add a UUID field to your Django model and populate it with values:</p><p><strong>1. models.py</strong></p><pre>import uuid<br>from django.db import models<br>class MyModel(models.Model):<br>    # ... other fields ...<br>    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)</pre><p>This snippet adds a uuid field to your model. default=uuid.uuid4 ensures a new UUID is automatically generated for each record. editable=False prevents manual editing, and unique=True enforces uniqueness across all records.</p><p><strong>2. Run </strong>makemigrations</p><p>When you run the command python manage.py makemigrations to create a migration for your model with the new UUIDField, Django might issue a warning:</p><pre>Callable default on unique field mymodel.uuid will not generate unique values upon migrating.<br>Please choose how to proceed:<br> 1) Continue making this migration as the first step in writing a manual migration to generate unique values described here: https://docs.djangoproject.com/en/5.0/howto/writing-migrations/#migrations-that-add-unique-fields.<br> 2) Quit and edit field options in models.py.   <br>Select an option:</pre><p>This warning appears <strong>only if your model already has existing data</strong>. This is because Django recognizes that simply adding the field with a callable default won’t populate the existing rows with unique UUIDs. It needs a way to generate and assign those values.</p><p>Choose option 1 to proceed. This acknowledges that you’ll be handling the unique value generation manually in your migration.</p><p><strong>3. The Migration Helper File</strong></p><p>Create a file named migration_helpers.py (or any name you prefer) in your app directory or a common location for utility functions. Then add the following code:</p><p>Python</p><pre># migration_helpers.py<br>import uuid<br>from django.db import migrations<br>class GenerateUUID(migrations.RunPython):<br>    def __init__(self, app_label, model_name, reverse_code=None, **kwargs):<br>        self.app_label = app_label<br>        self.model_name = model_name<br>        self.reverse_code = reverse_code or migrations.RunPython.noop<br>        super().__init__(self._gen_uuid, reverse_code=self.reverse_code, **kwargs)<br><br>    def _gen_uuid(self, apps, schema_editor):<br>        MyModel = apps.get_model(self.app_label, self.model_name)<br>        for row in MyModel.objects.all():<br>            row.uuid = uuid.uuid4()<br>            row.save(update_fields=[&quot;uuid&quot;])</pre><p><strong>4. The Migration File</strong></p><pre>#0002_add_uuid_to_mymodel.py<br>from django.db import migrations, models<br>import uuid<br># Import from your helper file<br>from .migration_helpers import GenerateUUID<br>class Migration(migrations.Migration):<br>dependencies = [<br>    (&quot;your_app_name&quot;, &quot;0001_initial&quot;), # Replace with your app and migration name<br>]<br>operations = [<br>  migrations.AddField(<br>    model_name=&quot;mymodel&quot;,<br>    name=&quot;uuid&quot;,<br>    field=models.UUIDField(default=uuid.uuid4, editable=False, null=True),<br>  ),<br>  GenerateUUID(<br>    app_label=&quot;your_app_name&quot;, # Replace with your app name<br>    model_name=&quot;MyModel&quot;, # Replace with your model name<br>    reverse_code=migrations.RunPython.noop,<br>  ),<br>  migrations.AlterField(<br>    model_name=&quot;mymodel&quot;, # Replace with your model name<br>    name=&quot;uuid&quot;,<br>    field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),<br>  ),<br>]</pre><p>This migration file adds the uuid field with null=True initially, then populates it with UUIDs for existing records using GenerateUUID, and finally sets the field to be unique, all in a single migration operation.</p><h3>A More Efficient Approach</h3><p>The Django documentation <a href="https://docs.djangoproject.com/en/5.0/howto/writing-migrations/#migrations-that-add-unique-fields">recommends a three-step process</a> for adding unique fields to existing models. This involves separate migrations for adding the field with null=True, populating UUID values, and finally altering the field to unique=True.</p><p>Our approach, however, achieves the same result in a single migration file with a single step. This simplifies the process and improves readability by encapsulating all the necessary actions within our custom GenerateUUID operation. This also provides a reusable class for generating UUIDs in other migrations, further enhancing development efficiency.</p><p><em>“This article was written with the assistance of an AI language model, which helped generate ideas and refine the text. The code examples, however, were written by me.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97eeb7cc5c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>