具有基于 Class 视图的 Django 多用户配置文件(最佳实践)

Django Multiple User Profiles with Class based views (Best Practices)

我有一个网站,其中有两种用户(比方说):学生和导师。

两种类型具有共同的登录功能、年龄、性别等,但具有不同的属性,例如学生的成绩单和导师的学位证书。

我阅读了这个问题:Django - Multiple User Profiles 并设置了我的配置文件,如下所示:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, related_name='profile')
    mobile = models.CharField(max_length=10, blank=False, null=True)
    picture = models.ImageField(
        upload_to='images/', default='images/newuser.png')
    age = models.IntegerField(null=True)
    slug = models.SlugField()
    ...

还有另外两个模型link到上面。例如:

class StudentProfile(models.Model):
    profile = models.ForeignKey(UserProfile, related_name="user_profile")
    #more custom attributes

class TutorProfile(models.Model):
   profile = models.ForeignKey(UserProfile, related_name="doctor_profile")
   #more custom attributes

现在我的问题:

1) SlugField 是在 UserProfile 属性上定义的,但理想情况下会使用 User.username 字段。这意味着这两个表之间的连接每次都会发生。这是意料之中的事吗?

2) 假设我使用的是基于 class 的视图,editing/viewing 配置文件将取决于所讨论的 UserProfile。但我希望用户能够 edit/view 在同一页面上查看他的所有详细信息。因此,我将不得不获取 TutorProfile / StudentProfile 并添加自定义逻辑以确保它们也发生更新。

我觉得应该有一个合适的方法来处理这些情况(因为很多网站都有类似的要求)。在这种情况下应遵循哪些最佳做法?

在寻找答案的过程中,我遇到了一个我认为可能适合我需要的解决方案(张贴在这里欢迎批评并帮助其他可能正在寻找答案的人)。

取自Django Design patterns and Best Practices

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, related_name='profile')
    mobile = models.CharField(max_length=10, blank=False, null=True)
    picture = models.ImageField(
        upload_to='images/', default='images/newuser.png')
    age = models.IntegerField(null=True)
    gender = models.IntegerField(null=True)
    user_type = models.CharField(max_length=20, choices=UserTypes.CHOICES)
    slg = models.SlugField()    

    class Meta(object):
        abstract = True


class StudentProfile(models.Model):
    report_card = models.FileField(upload_to="/temp")
    house = models.CharField()

    class Meta(object):
      abstract = True


class TutorProfile(models.Model):
    performance = models.IntegerField(default=0)
    salary = models.IntegerField(default=0)

    class Meta(object):
      abstract = True

一个基础摘要 class 和两个涵盖各种用户配置文件的特定 classes。像这样将它们分开使我们很容易推断出每种用户类型中存在的各个字段。 最后,

 class Profile(UserProfile, StudentProfile, TutorProfile):
     pass

这是用作 settings.AUTH_USER_MODEL 的模型。

总的来说,我看到的优点:

  1. 用户 edit/view 页面上的单个数据库调用。
  2. 更容易考虑整体。

缺点:浪费很多 space。

大家有更好的建议吗?