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 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?
No matter what strategy you pick, or what is your business model, always use one, and only one Django model to handle the authentication. You can still have multiple user types, but generally speaking it's a bad idea to store authentication information across multiple models/tables.
Groups: Way of Categorizing UsersDjango provides a basic view in the admin to create these groups and manage the permissions. The group denotes the “role” of the user in the system. As an “admin”, you may belong to a group called “admin”. As a “support staff”, you would belong to a group called “support”.
Django has Roles and Groups to categorise users. What is allowed and forbidden is controlled by Permissions. Every User, Role and Group can have different model-specific and view-specific Permissions. The system is quite complex and allows for many different setups.
For Django's default user model, the user identifier is the username, for custom user models it is the field specified by USERNAME_FIELD (see Customizing Users and authentication). It also handles the default permissions model as defined for User and PermissionsMixin .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With