Django中的用户模型继承和扩展
我想从内置类 User 继承 UserProfile 类,并进行 2 处修改:
1)用户名字段必须不唯一
2)电子邮件字段必须唯一
那么,如何通过 UserProfile 类覆盖这 2 个字段?
据我了解,我无法更改 User 类,所以我必须以某种方式在 UserProfile 类中进行此更改...... 但如何做到这一点??? 请帮助我!
提前致谢!!!!
I want to inherit UserProfile class from builtin class User with 2 modifications:
1) username field must be not unique
2) email field must be unique
So, how to override this 2 fields by UserProfile class?
As I understand I can't change class User, so I must do this changes in class UserProfile somehow...
But how to do that???
Help me please!
Thanks in advance!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你应该只是猴子补丁。
我自己从未这样做过,但深入研究这一点很有趣。查看模型字段初始化函数(我们需要在其中传递
unique=True
),它似乎只关心属性
_unique
是 True 还是 False。 Django 魔法的其余部分不应该关心该属性是如何设置的,所以让我们来猴子补丁吧!将猴子补丁应用程序放在
INSTALLED_APPS
中的某个位置,然后将其放入models.py
(自动加载):果然,django 生成以下 SQL:
I think you should just monkey patch.
I've never done this myself, but it was fun digging into this. Check out the model field init function (where we'd need to pass
unique=True
)All it seems to care about is that an attribute
_unique
is True or False. The rest of django magic shouldn't care how that attribute was set, so let's monkey patch!Put a monkey patch app somewhere in your
INSTALLED_APPS
, and put this in yourmodels.py
(which is auto loaded):Sure enough, django generates the following SQL: