django - 对于我所有的外键,我应该在 Django 中使用 User 还是 UserProfile?

标签 django django-models

这是我遇到的情况。

我有 User 和 ProfileUser。我想向模型添加额外的逻辑,但由于我无法将它添加到 Django 用户模型,所以我必须将它添加到 ProfileUser。目前我所有的模型都有外键(用户)。我应该像那样保留它们还是应该在我的其他模型上使用 ForeignKey(UserProfile)?

如果我保留 ForeignKey(User),我的观点示例:

class myview(request):
    user = request.user
    userProfile = user.get_profile()
    neededStuff = userProfile.get_needed_stuff()

然后在 UserProfile 模型中:

def get_needed_stuff(self):
    user= self.user # Or actually, is this right 
    goals = Goal.objects.get(<conditions that i wont bother writing here>)
    return goals

那么对于这种情况,为了网站的进一步发展,我应该使用哪个外键?

最佳答案

我认为你应该使用 User. UserProfile 应该是自定义的,并且可以在每个项目上有所不同。因此,如果您将对另一个项目使用相同的代码,您可能会因此而失败。此外,在代码中获取用户对象总是很容易,因此您可以毫无问题地获取配置文件 user.get_profile() 如您所示(并不总是需要配置文件)。所以总的来说,我认为使用其他模块并只传递用户对象(或 ID)而不是个人资料会更容易。

也可能是解决方案 - 编写您自己的类,它将对用户负责。只需编写方法来返回配置文件、返回 stuff_needed 或您想要的任何内容,只需传递用户对象和关于您想要的内容的附加参数即可。

简而言之,我支持使用 User 作为外键,因为在我看来它更合乎逻辑,而 User 模型始终是主要模型(您始终拥有它)而 UserProfile 只是扩展。

伊格纳斯

关于django - 对于我所有的外键,我应该在 Django 中使用 User 还是 UserProfile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5902531/

相关文章:

python - Django 在用户模型中显示多对多关系

python - 在 OSQA (django python) 上添加问题时,其正文为空

python - 在 Django 中获取自己的应用程序

Django url 模板标签给出 NoReverseMatch 错误

django - super 用户创建 NOT NULL 约束出错失败

python - 获取模型过滤器以显示事件值的计数

django-models - Django : Verbose name of related model not translated

django - 如何配置 Postgres 与 pytest 一起使用

django - 原子事务不起作用 django rest

python - 使用 Django 模型的促销代码