在Django中扩展现有的User模型

时间:2021-07-06 19:20:50

Let's say I have an app that has 3 kinds of user

假设我有一个有3种用户的应用程序

  • Employee with fields like work_number, department etc.
  • 员工有work_number,department等字段。
  • Member with fields like phone_number, .....
  • 会员拥有phone_number,.....等字段
  • Agent with fields like company_name,.....
  • 具有company_name,.....等字段的代理

They're different.

他们是不同的。

I write models like this:

我写这样的模型:

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)
    .......

class Member(models.Model):
    user = models.OneToOneField(User)
    .......

class Agent(models.Model):
    user = models.OneToOneField(User)
    .......

Now I can :

现在我能 :

u = User.objects.get(username='xxxx')
u.employee // it works...

but, ONE user has THREE profiles (employee,member,agent) !!!

但是,一个用户有三个配置文件(员工,会员,代理商)!

It's not matches my business, the business role is ONE user could be and must be only one kind of 3 profiles.

它与我的业务不匹配,业务角色是一个用户可能并且必须只是一种3个配置文件。

What's the best way to solve this?

解决这个问题的最佳方法是什么?

1 个解决方案

#1


1  

Why not have a single profile with a role associated (even if certain fields will never be filled for a specific role)?

为什么不将一个具有关联角色的配置文件(即使特定角色永远不会填充某些字段)?

You can handle the validation through forms and instead having 3 different models you would have 3 different forms.

您可以通过表单处理验证,而不是有3种不同的模型,您将有3种不同的形式。

#1


1  

Why not have a single profile with a role associated (even if certain fields will never be filled for a specific role)?

为什么不将一个具有关联角色的配置文件(即使特定角色永远不会填充某些字段)?

You can handle the validation through forms and instead having 3 different models you would have 3 different forms.

您可以通过表单处理验证,而不是有3种不同的模型,您将有3种不同的形式。