Modeling accounts for different types of users in Django
Say that you have an application where different kind of users can sign: Firms, Lawyers, and Clients. A Firm has many lawyers; a lawyer has many clients. The views for a firm user are, of course, different from the views of a lawyer user; the two are different from the client user.
How would you model the three different users? I can think the following approach:
Three different models with a ForeignKey
to User
, each with their own fields, e.g.:
class Firm(models.Model):
user = models.ForeignKey(User)
class Lawyer(models.Model):
user = models.ForeignKey(User)
specialty = models.CharField(max_length=100)
class Client(models.Model)
user = modelsForeignKey(User)
Now you can create, for instance, consultations as a separate model using two ForeignKeys
: to Lawyer
and to Client
; you开发者_JAVA百科 can also add resources to a consultation (like documents, or stuff like that) by creating a model Resource
with a ForeignKey
to Consultation
.
This approach makes it difficult to distinguish among users: how do you know whether a user
is a Firm
, for instance - you need to query the database several times or assign a Profile
to the generic User
object.
You could also add only a Profile
to the User
and include a Role
, and then you channel the views and authentication based on user.get_profile().role
.
How would you deal with this problem?
I would do what you suggest here:
You could also add only a Profile to the User and include a Role, and then you channel the views and authentication based on user.get_profile().role.
Create a profile with a choice field for the role. Create some decorators like @lawyer_only that make sure that your views are only accessibly by Lawyer role users.
You could also consider subclassing the User model (model inheritance): http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance
You will have to go with the option of multi-table inheritance http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance since the User class is not an abstract model.
精彩评论