具有多个相互属性的多种类型的用户

时间:2016-07-05 07:55:12

标签: python django django-models django-users

如何创建具有多个相互属性的两个User类型?据我所知,创建两种User的最佳做法是创建2 UserProfiles。我有类型 - FirmPerson。所以我决定创建两个UserProfiles

class FirmProfile(models.Model):
    user = models.OneToOneField(User, related_name='firmprofile')
    prefered_times = ...
    favourite_food = ...

class PersonProfile(models.Model):
    user = models.OneToOneField(User, related_name='personprofile')
    prefered_times = ...
    favourite_food = ...

现在,我正在寻找一种我不必两次写出这些属性的方法。可能吗?

编辑:我已经创建了这个,但我不确定它是否是最佳选择,因为每个UserProfile都有两个配置文件 - 公司和个人

class UserProfile(User):
    user = models.OneToOneField(User, related_name='userprofile')

    TYPE_OF_USER_CHOICES = (('firm','Firm'),
                            'person','Person')

    type_of_user = models.CharField(max_length=40, choices=TYPE_OF_USER_CHOICES)

class FirmProfile(models.Model):
    user = models.OneToOneField(User, related_name='firmprofile')

class PersonProfile(models.Model):
    user = models.OneToOneField(User, related_name='personprofile')

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点https://docs.djangoproject.com/en/1.9/topics/db/models/#model-inheritance

最简单的是创建abstract模型

class BaseProfile(models.Model):
    prefered_times = ...
    favourite_food = ...

    class Meta:
        abstract = True

class FirmProfile(BaseProfile):
    user = models.OneToOneField(User, related_name='firmprofile')
    ... # all custom fields can be defined here

class PersonProfile(BaseProfile):
    user = models.OneToOneField(User, related_name='personprofile')
    ...

回答评论 你可以检查这样的用户类型

def get_user_type(user):
    if getattr(user, 'firmprofile', None):
        return 'firm'
    elif getattr(user, 'personprofile', None):
        return 'person'
    else:
        return None