[Answered ]-Implicit UUID auto fields for primary keys in Django

1👍

A not very well known feature is that you can set the DEFAULT_AUTO_FIELD setting [Django-doc] to specify the primary key used by all models, except stated differently in the model itself, or the app config. Now one of the problems is that Django currently does not like the idea very much to plug in a UUIDField, but we can "force" this by specifying our own with:

# app_name/fields.py

import uuid

from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.models import AutoField, UUIDField

BaseDatabaseOperations.integer_field_ranges['UUIDField'] = (0, 0)


class UUIDAutoField(UUIDField, AutoField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('default', uuid.uuid4)
        kwargs.setdefault('editable', False)
        super().__init__(*args, **kwargs)

and then plug the UUIDAutoField as default field:

# settings.py

# …

DEFAULT_AUTO_FIELD = 'app_name.fields.UUIDAutoField'

That being said, in my humble opinion, it was a bit of a misfeature to map an AutoField to an int and vice versa. One could make a separate type for each model like a UserPk class, that wraps an int and thus disables arithmetic on that field (since adding two UserPks together makes not much sense), and introduce type chekcs such that if you filter on User.objects.filter(pk=42), it errors if 42 is a simple int, or some primary key of another model. Haskell’s esqueleto [hackage] follows this idea.

0👍

May be you are looking for :

 id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 

Leave a comment