Django:为什么要创建一个OneToOne到UserProfile,而不是auth.User的子类化? [英] Django: Why create a OneToOne to UserProfile instead of subclassing auth.User?

查看:134
本文介绍了Django:为什么要创建一个OneToOne到UserProfile,而不是auth.User的子类化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:如果你想通过告诉我你不喜欢django.contrib.auth来回答这个问题,请继续前进。这不会有帮助我很清楚这个问题的意见的范围和实力。



现在,问题是:



约定是创建一个模型,UserProfile,一个OneToOne到用户。



在我想到的每一个方面,一个更有效和有效的方法是将User一个打算用于系统中每个人的课程 - 一个称为Person(User)的类。



我没有看到一个一致的解释,为什么前者是常规的,后者被认为是黑客。前一段时间,我改用了OneToOne方法,以获得使用get_profile()的能力,并且我从此后悔过。我正在考虑切换,除非我能够理解这种方法的优点。

解决方案

你意识到,没有你,那个模型子类是通过一个OneToOne关系来实现的?事实上,就效率而言,这两种方法之间根本看不出任何区别。



在我看来,现有的具体模型的子类别是一个讨厌的如果可能的话,应该避免这种攻击。它涉及隐藏数据库关系,以便在执行额外的数据库访问时不清楚。明确显示关系,并在必要时明确地访问它们是非常明确的。



现在,我想要的第三个替代方法是创建一个全新的用户模型具有返回新模型而不是默认模型的实例的自定义身份验证后端。创建后端只涉及定义一些简单的方法,所以很容易做到。


Note: If you are tempted to 'answer' this question by telling me that you don't like django.contrib.auth, please move on. That will not be helpful. I am well aware of the range and strength of opinions on this matter.

Now, the question:

The convention is to create a model, UserProfile, with a OneToOne to User.

In every way I can think of, a more efficient and effective approach is to subclass User to a class that one intends to use for every human in the system - a class called, say, Person(User).

I have not seen a coherent explanation of why the former is conventional and the latter is regarded as a hack. A while ago, I changed over to the OneToOne approach so as to gain the ability to use get_profile() and I have regretted it ever since. I'm thinking of switching back unless I can be made to understand the advantage of this approach.

解决方案

You do realise, don't you, that model subclassing is implemented by means of a OneToOne relationship under the hood? In fact, as far as efficiency is concerned, I cannot see any difference at all between these two methods.

Subclassing of existing concrete models is, in my opinion, a nasty hack that should be avoided if at all possible. It involves hiding a database relationship so that it is unclear when extra db access is performed. It's much clearer to show the relationships explicitly, and access them explicitly where necessary.

Now, a third alternative which I do like is to create a completely new User model, along with a custom authentication backend that returns instances of the new model instead of the default one. Creating a backend only involves defining a couple of simple methods, so it's very easy to do.

这篇关于Django:为什么要创建一个OneToOne到UserProfile,而不是auth.User的子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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