将便利方法添加到 Django Auth User 模型的最佳方法? [英] Best way to add convenience methods to a Django Auth User model?

查看:30
本文介绍了将便利方法添加到 Django Auth User 模型的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 django.contrib.auth.models.User 模型添加一个方便/模型方法.这样做的最佳做法是什么,因为上次我检查时,扩展 User 模型被认为是不好的做法.

I want to add a convenience/model method to the django.contrib.auth.models.User model. What is the best practice for doing this since, last time I checked, extending the User model was considered bad practice.

我有一个单独的自定义 UserProfile 模型.我应该将它用于所有与用户相关的便捷方法吗?

I have a separate custom UserProfile model. Should I be using that for all User-related convenience methods?

推荐答案

这取决于您要添加到模型中的内容.如果你想添加更多关于用户的信息,那么一般建议你使用UserProfile方法:http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

It depends what you are trying to add to the model. If you want to add more information about the user, then it is generally recommended that you use the UserProfile method: http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

但是,如果您只想向 User 模型添加自定义方法或管理器,我会说使用代理模型更合乎逻辑,如下所示:

However, if you just want to add custom methods or managers to the User model, I would say that it's more logical to use a proxy model, like so:

from django.contrib.auth.models import User

class UserMethods(User):
  def custom_method(self):
    pass
  class Meta:
    proxy=True

代理模型将在与原始模型相同的数据库表上运行,因此非常适合创建自定义方法而无需物理扩展模型.只需将视图中对 User 的任何引用替换为 UserMethods.(当然,您可以通过取消注册 User 模型并注册您的代理模型来代替它在管理工具中使用它.)

A proxy model will operate on the same database table as the original model, so is ideal for creating custom methods without physically extending the model. Just replace any references to User in your views to UserMethods. (And of course you can use this in the admin tool by unregistering the User model and registering your proxy model in its stead.)

创建的原始 User 模型的任何实例都可以通过 UserMethods 模型立即访问,反之亦然.更多信息:http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models

Any instances of the original User model that are created will be instantly accessible via the UserMethods model, and vice-versa. More here: http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models

(注意,代理模型需要 Django 1.1 及更高版本)

(NB. Proxy models require Django 1.1 and above)

这篇关于将便利方法添加到 Django Auth User 模型的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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