Django:自定义用户模型的返回字段 [英] Django: Customize the User model's return field
问题描述
Django用户模型的默认返回字段是'username'.但是,我的应用程序需要它为"first_name".目前,我只是派生了Django,并对User模型进行了更改:
The default return field of Django's User model is 'username'. However, my application needs it to be 'first_name'. Currently, I just forked Django and made this change to the User model:
def __str__(self):
return self.first_name
它工作正常,但是我想知道是否还有其他简单的方法可以在不派生Django的情况下做到这一点?
It works fine, but I wonder if there are other SIMPLE ways of doing this without forking Django?
推荐答案
有一种方法可以在 User
类上注入新方法.
There is a way to inject a new method on your User
class.
from django.contrib.auth.models import User
def get_first_name(self):
return self.first_name
User.add_to_class("__str__", get_first_name)
您可以将其放在 common
应用程序中(最好放在 models.py
内部)
You can put this in a common
application (preferably inside models.py
)
不是很干净,但是如果您只需要进行一次更改,则可以完成这项工作而不会覆盖整个 User
模型.
Not very clean, but does the job without overriding the entire User
model, if you only need this single change.
这篇关于Django:自定义用户模型的返回字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!