如何在 Django 中创建一个不需要提供默认函数的 UUIDField,而不是 returns 数据库生成的 UUID?

How to create a UUIDField in Django that doesn't require the default func to be provided, instead returns UUID generated by the DB?

目前 的最佳答案是

When you use UUIDField as a primary key in Django, it doesn't generate a UUID one for you, you generate it yourself before you save the object

但我认为应该可以破解一个允许基于数据库的 UUID 生成的解决方案。

在 postgres 中安装 uuid-ossp 扩展后

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

我认为它应该或多或少像 AutoField 一样工作。

如果原始 sql 已用于 table 创建

CREATE TABLE example(
   id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
);

然后原始插入将return一个新的随机UUID作为id字段。

如何创建自定义 Field 以便此原始解决方案与 Django ORM 一起工作?

我刚刚 运行 解决了我一年前提出的这个问题。 Django 为您提供了 RandomUUID,它在 PostgreSQL 中调用 gen_random_uuid

用法示例:

from django.contrib.postgres.functions import RandomUUID

class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, default=RandomUUID)

其中RandomUUID

class RandomUUID(Func):
    template = 'GEN_RANDOM_UUID()'
    output_field = UUIDField()

对于 13 以下的版本 PostgreSQL docs 提及调用 gen_random_uuid

Returns a version 4 (random) UUID. (Obsolete, this function is now also included in core PostgreSQL.)

它已过时,因为“在 pgcrypto 中已过时”扩展。

在 13 版及更高版本的 PostgreSQL 文档中,您可以找到 第 9 章函数和运算符中提到的 this function 节。

This function returns a version 4 (random) UUID. This is the most commonly used type of UUID and is appropriate for most applications.