Django and uuid with PostgreSQL

317 views
Skip to first unread message

Andrea Posi

unread,
Oct 18, 2016, 9:15:46 AM10/18/16
to Django users
I'm creating a rest api using Django and DRF. I don't want to expose IDs directly to clients so I'm trying to setup my models like this example:

class AbstractGuidModel(models.Model):
    uuid = models.UUIDField(blank=True, default=uuid.uuid4, unique=True, editable=False)

    class Meta:
        abstract = True

class MyModel(AbstractGuidModel):
    name = models.CharField(max_length=NAME_LENGTH)

Since the AbstractGuidModel has default=uuid.uuid4, uuid are generated by python code and migrations look like:

CREATE TABLE "MyModel" ( ... "uuid" uuid NOT NULL UNIQUE, ... );

I've read Postgres has an extension for generating automatically uuids.

Once extension is installed, how can I tell django to let database use his own extension and not letting him create them with the Python uuid module?

Tim Graham

unread,
Oct 18, 2016, 8:14:23 PM10/18/16
to Django users
The SQL looks correct -- it's not using anything Python related. Are you encountering some error?

Andrea Posi

unread,
Oct 19, 2016, 2:58:30 AM10/19/16
to Django users
Yes, it is actually correct, but I'd just like to force uuid generation at database level (postgres supports it) and not via python/django

I can modify the table with raw sql after migration and disable
default=uuid.uuid4
inside django models, but I'm looking for a better way to accomplish it
Reply all
Reply to author
Forward
0 new messages