【问题标题】:Django user with custom data in multiple apps在多个应用程序中具有自定义数据的 Django 用户
【发布时间】:2015-02-06 11:26:37
【问题描述】:

客户用户模型很棒,但如果您想构建一个组合多个应用程序的项目,每个应用程序都可以假设它会将用户模型作为其模型的一部分。我的计划是恢复到标准 django 用户并在每个应用程序中都有一个配置文件。

例如。

app1.models.py

from django.contrib.auth.models import User

Class App1User(models.Model):
    user = models.OneToOne(User)
    special = models.CharField( some field that relates to the user in this app)

app2.models.py

from django.contrib.auth.models import User

Class App2User(models.Model):
    user = models.OneToOne(User)
    another = models.CharField( some field that relates to the user in this app)

等等

然后添加代码以在需要时获取相关的配置文件数据,可能会添加一些中间件或模板上下文处理器。在我走这条路之前,我想检查一下这是最 Djangoeque 的解决方案吗?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    恕我直言,你做对了。

    而且您不需要任何中间件或上下文处理器来为用户获取相关数据。 OneToOne 字段可以作为user 实例的属性轻松访问:

    {{ user.app1user.special }}
    {{ user.app2user.another }}
    

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 2017-03-04
      • 2011-08-17
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多