且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用UUID作为Django模型中的主键(通用关系影响)

更新时间:2023-01-30 10:58:49

UUID主键不仅会导致通用关系的问题,而且通常会带来效率:每个外键都会显着更昂贵存储和加入机器字。

A UUID primary key will cause problems not only with generic relations, but with efficiency in general: every foreign key will be significantly more expensive—both to store, and to join on—than a machine word.

但是,无需UUID作为主键:只需将其设为辅助键,通过用 unique = True 的uuid字段补充您的模型。使用隐式主键(正常(系统内部)),并使用UUID作为外部标识符。

However, nothing requires the UUID to be the primary key: just make it a secondary key, by supplementing your model with a uuid field with unique=True. Use the implicit primary key as normal (internal to your system), and use the UUID as your external identifier.