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

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

问题描述

注意:如果你想通过告诉我你不喜欢 django.contrib.auth 来回答"这个问题,请继续.那不会有帮助.我很清楚关于这个问题的意见的范围和强度.

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.

现在,问题:

约定是创建一个模型 UserProfile,与 User 的 OneToOne.

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

在我能想到的各个方面,一种更高效和有效的方法是将 User 子类化为一个打算供系统中的每个人使用的类 - 一个名为 Person(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).

我还没有看到为什么前者是传统而后者被视为黑客的连贯解释.前段时间,为了获得使用 get_profile() 的能力,我改用 OneToOne 方法,从那时起我就后悔了.除非我能够理解这种方法的优点,否则我正在考虑切换回去.

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.

推荐答案

您确实意识到,不是吗,模型子类化是通过内部的 OneToOne 关系实现的?事实上,就效率而言,我看不出这两种方法有什么区别.

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.

现在,我喜欢的第三种选择是创建一个全新的 User 模型,以及一个自定义身份验证后端,该后端返回新模型的实例而不是默认模型.创建后端只需要定义几个简单的方法,所以很容易做到.

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天全站免登陆