【发布时间】:2018-01-24 14:43:02
【问题描述】:
寻找一种将一个字段添加到 Django's User 模型的最简单方法。
我有两种类型不同的用户——公司和客户,所以我决定创建两种类型的UserProfiles。 CompanyProfile 和 CustomerProfile。每个用户都有CompanyProfile 或CustomerProfile。
为了能够filter 并决定它是哪种类型,我想将type 字段添加到User 模型中。
你有什么建议?现在我在中间有UserProfile,这似乎有点矫枉过正,它使过滤、查找和许多其他事情变得不那么简单。
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile')
type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USERPROFILE_TYPE_CHOICES)
company_profile = models.OneToOneField('CompanyProfile', null=True, blank=True, on_delete=models.CASCADE,
related_name='userprofile')
customer_profile = models.OneToOneField('CustomerProfile', null=True, blank=True, on_delete=models.CASCADE,
related_name='userprofile')
我正在考虑创建我的自定义User
模型。
class User(AbstractBaseUser):
type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USER_TYPE_CHOICES)
USERNAME_FIELD = 'username'
但是Django 说没有像username 这样的字段,我想避免手动编写整个User 模型及其所有字段。
编辑
我知道我可以根据customerprofile__isnull=False 进行过滤,所以实际上我根本不需要type 字段,但它看起来并不是最好的方法。
【问题讨论】:
-
你应该继承
AbstractUser,而不是AbstractBaseUser。后者只有两个字段:password和last_login,而前者本质上是默认的User,只是抽象的。
标签: python django django-users django-2.0