【发布时间】:2017-11-26 14:02:00
【问题描述】:
标题可能看起来很熟悉(很多相关问题,但我找不到与我的用例相关的问题)。
这是我的应用信息:
- 两种类型的用户配置文件(基本和专业)
- 基本用户是
User的一个实例,带有一个附加字段 (phone) - 基本用户发布问题(需要帮助)
- 专业用户提供各种服务(帮助/回答基本用户发布的问题)
- 专业用户属于
Organisation类,基本用户不属于。 - 另外,Pro 代表它自己的组织,所以
Organisation属于一个配置文件(因此OneToOneField)
问题:所以我需要帮助来决定是为每种类型创建两个单独的配置文件(BasicProfile 和 ProProfile),还是创建一个 Profile 并使用一个布尔字段表示个人资料是否is_pro或不是(很像django的is_superuser布尔字段)
方法一:
class Organisation(models.Model):
name = models.CharField(_('Name'), max_length=50)
profile = models.OneToOneField(ProProfile, on_delete=models.CASCADE)
...
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
phone = models.CharField(_('Phone'), max_length=200, null=True, blank=True)
class Meta:
abstract = True
def __str__(self):
return self.user.get_full_name()
class UserProfile(Profile):
pass
class ProProfile(Profile):
verified = models.BooleanField(default=False, verbose_name=_('Verified'))
方法二:
class Organisation(models.Model):
name = models.CharField(_('Name'), max_length=50)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
class ProfileManager(models.Manager):
def basic(self, **kwargs):
return self.filter(is_pro=False, **kwargs)
def pro(self, **kwargs):
return self.filter(is_pro=True, **kwargs)
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
phone = models.CharField(_('Phone'), max_length=200, null=True, blank=True)
verified = models.BooleanField(default=False, verbose_name=_('Verified'))
is_pro = models.BooleanField(default=False)
objects = ProfileManager()
def __str__(self):
return self.user.get_full_name()
目前,这些配置文件没有太多功能(字段),但将来可能会获得一些额外的字段。
如果将更多字段/功能添加到用户配置文件中,您个人更喜欢哪种方法更具可读性、可扩展性/可维护性?
一些用例:
p = company.profile(方法二)
p = company.proprofile(约1)
if company.profile.is_pro: # (Appr 2)
do_something()
在用户注册时创建配置文件实例,然后:
p = ProProfile.objects.create(user=self.user, phone=phone)
org = form.cleaned_data['org']
Organisation.objects.create(name=org, profile=p) <-- This is simplified version, I do extra validation before creating org)
此外,每种配置文件类型都有自己的仪表板版本。当Pro 登录时,他/她会看到更多内容、基本用户发布的任务列表、组织详细信息、潜在客户等。
编辑:此外,使用方法 1,从 request.user 获取配置文件将是一个命中注定的案例,例如
try:
request.user.proprofile
# it's Pro
except RelatedObjectDoesNotExist:
# it's basic
pass
提前致谢。
【问题讨论】:
标签: django django-models