[Solved]-Adding a Non-Primary Key AutoField or a 'serial' field in a Django Model which uses a UUID field as a Primary Field

4👍

Tried this as well. My workaround was to use raw SQL instead.

Migration:

migrations.RunSQL(
    "CREATE SEQUENCE sequence_name START 100000",
    reverse_sql="DROP SEQUENCE IF EXISTS sequence_name",
    elidable=False,
),

Model:

def get_next_increment():
    with connection.cursor() as cursor:
        cursor.execute("SELECT nextval('sequence_name')")
        result = cursor.fetchone()
        return result[0]

class MyModel(models.Model):
    my_field = models.IntegerField(default=get_next_increment, editable=False, unique=True)

0👍

For the sake of example, lets assume the name of our table is payouts

Below will be the model for payouts:

class Payouts(models.Model):
    # seq_id = models.IntegerField() 
    # we will create seq_id auto-increment by raw SQL
    id = models.UUIDField(primary_key=True)

    class Meta:
        managed = True
        db_table = 'payouts'

You can see that we want to have id with uuid as primary key.

Follow the instructions below:

Step 1: Make migrations file for the model above.

python manage.py makemigrations

Step 2: Generate an empty migration to execute SQL queries:

python manage.py makemigrations  --empty -n dont_delete_add_defaults_sql

Step 3: Edit dont_delete_add_defaults_sql as below:

from django.db import migrations    

class Migration(migrations.Migration):

    dependencies = [
        ('apiapp', '0001_initial'), #Replace 0001_initial with the name of file generated in step 1
    ]

    operations = [
        migrations.RunSQL("ALTER TABLE payouts ADD seq_id serial NOT NULL;"),
        migrations.RunSQL("DROP SEQUENCE IF EXISTS payouts_seq_id_seq CASCADE;"),
        migrations.RunSQL("create sequence payouts_seq_id_seq owned by payouts.seq_id;"),
        migrations.RunSQL("alter table payouts alter column seq_id set default nextval('payouts_seq_id_seq');"),
    ]

Step 4: Run the final migrations

python manage.py migrate

Leave a comment