在 Django 中扩展 contrib 模型的字段
这种情况我已经遇到过好几次了。
如果我在 contrib 中有一些我通常喜欢的东西,但我想对某个字段进行一些小的调整,我该怎么办?
我不想把孩子和洗澡水一起倒掉。
举个例子,以 auth.user 为例(与人们对此事的普遍看法相反,我认为它总体上是在正确的轨道上)。我想为 auth.user 与 auth.group 的关系创建一个直通模型。
我怎样才能在不修改 django 的情况下做到这一点?
I have come across this situation several times.
If I have something that I generally like in contrib, but I want to make one minor tweak to a field, what do I do?
I don't want to throw out the baby with the bathwater.
To give an example, take auth.user (which, contrary to what seems to be popular opinion on the matter, I regard as being generally on the right track). I want to create a through model for auth.user's relationship to auth.group.
How can I do this without modifying django?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
auth.User
是一种特殊情况,因为 User 模型与 Django 的许多部分相关联,并且修改它很棘手(尽管并非不可能,正如其他人指出的那样)。我最好的建议是质疑为什么你不想修改 Django 源代码。您可以拉取开发分支头部的源代码,也可以获取与编号版本相对应的标记版本。随意修改代码并使用svn update
、svn diff
和svn patch
的某种组合来迁移您的更改。接下来,可以在代码中修改 contrib 模块,因为 Python 是解释型和动态类型的。如果这样做,您需要考虑解析/处理顺序,因为某些操作可能已经使用了原始模块。下面是我从其他人那里得到的一个示例(可能是在 SO 上),说明如何从
User
添加方便的前向引用到关联的Profile
对象:我不认为但是,此策略适用于在 django.contrib.auth.models.User 中添加/修改 ModelFields 。
最后,对于将组与用户关联的具体示例,您应该通过 创建 UserProfile 模型。我最初的猜测是这应该很容易。
auth.User
is a special case since the User model is tied in to lots of parts of Django and it is tricky to modify this (though not impossible, as others have pointed out). My best advice would be to question why you don't want to modify Django source. You can pull source for either the head of the devel branch or get a tagged version corresponding to a numbered release. Modify the code at will and use some combination ofsvn update
,svn diff
, andsvn patch
to migrate your changes.Next, modifications to contrib modules are possible in your code, since Python is interpreted and dynamically typed. If you do this, you'll need to take into consideration parsing/processing order since some operations may already have utilized the original module. Below is an example I got from someone else (probably here on SO) of how to add a convenient forward reference from
User
to the associatedProfile
object:I don't think this strategy will work for adding/modifying
ModelFields
indjango.contrib.auth.models.User
, however.Finally, for your specific example of associating groups with a user, you should see if this is possible by creating a UserProfile model. My initial guess is that it should be pretty easy.