django用户模型和自定义主键字段 [英] django user model and custom primary key field

查看:120
本文介绍了django用户模型和自定义主键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,Django在每个名为 id 的模型上创建主键字段,类型为 AutoField 。在我的模型上,我通过使用 primary_key 将其重写为使用自定义 UUIDField 作为主键属性。我还希望 django.contrib.auth 中的 User 模型具有 UUIDField 作为主键,但是如果不更改 User 模型源代码,这似乎是不可能的。

Django by default makes a primary key field on each model named "id", with a type of AutoField. On my models, I'm overriding this to use a custom UUIDField as the primary key by using the "primary_key" attribute. I would also like the User model in django.contrib.auth to have a UUIDField as the primary key, but this doesn't seem to be possible without changing the User model source code.

有没有建议的方法来解决此问题?

Is there any recommended way to approach this problem?

推荐答案


在不更改用户模型源代码的情况下似乎是不可能的。

this doesn't seem to be possible without changing the User model source code.

正确。除非您愿意更改(或替换) User ,否则没有办法。

Correct. Unless you are willing to change (or replace) User there isn't a way.

一个(连续, hackish)的方法是为每个 User 实例附加一个 UserProfile 。每个 User 应该具有一个一个 UserProfile 。然后,您可以将 UUIDField 添加到配置文件中。您仍然必须执行自定义查询才能将 UUIDField 转换为 id

One (tenuous, hackish) way to do this would be to attach an UserProfile for each User instance. Each User should have exactly one UserProfile. You can then add your UUIDField to the profile. You will still have to do custom querying to translate from UUIDField to id.

如果您不喜欢 UserProfile 这个名称,则可以适当地重命名。关键是您与 User 有一对一的关系。

If you don't like the name UserProfile you can rename it suitably. The key is that you have a one-to-one relationship to User.

这篇关于django用户模型和自定义主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆