在 django 中为不同类型的用户提供不同的配置文件的最佳方法是什么?

发布于 2024-07-15 03:50:42 字数 119 浏览 7 评论 0原文

在我的申请中,我有学生、教授和工作人员。 工作人员不需要个人资料,但教授和学生各自需要不同的个人资料。 我不想自己全部实现(中间件之类的),那么有没有办法让 get_profile() 根据用户的角色返回不同的配置文件?

In my application I have students, professors and staff. Staff members do not need a profile but professors and students each need a different profile. I'd rather not implement it all myself (middleware and whatnot), so is there anyway to just have get_profile() return a different profile depending on a user's role?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

莫多说 2024-07-22 03:50:42

使用目前处于测试阶段的 Django 1.1,我将实现 代理模型

class MyUser(User):

  class Meta:
    proxy = True

  def get_profile(self):
    if self.role == 'professor':
      return ProfessorProfile._default_manager.get(user_id__exakt=self.id)
    elif self.role == 'student':
      return StudentProfile._default_manager.get(user_id__exakt=self.id)
    else:
      # staff
      return None

get_profile需要原始的缓存代码等等。 但本质上你可以做类似的事情。

使用 Django 1.0.x,您可以基于 User 实现派生类,但这可能会破坏其他地方的代码。 对于类似的东西,我喜欢代理类,它只添加 python 功能而不改变数据库模型。

With Django 1.1, which is currently in beta, I would implement a proxy model.

class MyUser(User):

  class Meta:
    proxy = True

  def get_profile(self):
    if self.role == 'professor':
      return ProfessorProfile._default_manager.get(user_id__exakt=self.id)
    elif self.role == 'student':
      return StudentProfile._default_manager.get(user_id__exakt=self.id)
    else:
      # staff
      return None

get_profile needs the caching code from the original and so on. But essentially you could do something like that.

With Django 1.0.x you could implement derived classes based on User, but this might break code in other places. For stuff like that I love proxy classes, which just add python functionality without changing the database models.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文