Django基于类视图的多个用户配置文件(最佳实践)

时间:2016-04-04 14:04:02

标签: django django-models django-views django-class-based-views

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

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

我已阅读此问题: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()
    ...

另外两个与上述相关的模型。例如:

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)SlugFieldUserProfile属性上定义,但理想情况下会使用User.username字段。这意味着每次都会发生这两个表之间的连接。这是预期的吗?

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

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

1 个答案:

答案 0 :(得分:2)

在寻找答案的过程中,我遇到了一个我认为可能符合我需求的解决方案(在此发帖以欢迎评论并帮助其他可能寻找答案的人)。

取自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 Profile(UserProfile, StudentProfile, TutorProfile):
     pass

这是用作settings.AUTH_USER_MODEL的模型。

总的来说,我看到了优势:

  1. 用户edit / view页面上的单个数据库调用。
  2. 更容易思考整体。
  3. 缺点:浪费了很多空间。

    任何人都有更好的建议吗?

相关问题