Django, User can have more than one role in the application, 3 types of User

As title, I have 3 types of User and each User can have more than one role.

from django.contrib.auth.models import AbstractUser, User
from django.db import models
from django.db.models import CASCADE
from hospital.models import Hospital

class Role(models.Model):
  The Role entries are managed by the system,
  automatically created via a Django data migration.
    DOCTOR = 1
    DIRECTOR = 2
    PATIENT = 3

        (DOCTOR, 'doctor'),
        (DIRECTOR, 'director'),
        (PATIENT, 'patient'),


    id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True)

    def __str__(self):
        return self.get_id_display()

class User(AbstractUser):
    roles = models.ManyToManyField(Role)

    def __str__(self):
        return self.roles

class Doctor(models.Model):
    # role = models.OneToOneField(User, on_delete=CASCADE)
    career = models.TextField(blank=True, max_length = 1000)

class Director(models.Model):
    # role = models.OneToOneField(User, on_delete=CASCADE)
    members = models.ManyToManyField(Doctor)

class Patient(models.Model):
    # personal information like above.

I'm creating a model, but I do not know how to set the key.

I made it by referring to the above site. The director owns the doctor and can authorize it.

But I do not know how to give a key to a doctor or director.

If you I to comment, I get an error.

I hope you can help me.

1 answer

  • answered 2018-02-18 08:58 Ashish Nitin Patil

    Assuming that you want to set the default roles for the 3 derived classes.

    Taking slight inspiration from this post.

    Since roles is a many-to-many relation, you can override the model's save method (you can use signals for this as well, but wouldn't recommend that in your case).


    class Doctor(models.Model):
        def save(self, *args, **kwargs):
            if not # object creation
                should_add_role = True
            super(Doctor, self).save(*args, **kwargs) # do the usual
            if should_add_role: # add our defaults