How to assign foreign key to a custom user model which has a specific role ?

In my AUTH_USER_MODEL, there are three type of roles: Student, Tutor, Superuser. I want to assign foreign key in Roadmap to Tutor only (Which point to a specific role only), not for all the users. How should I make it ?

class Roadmap(models.Model):
    ...
    tutor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Here is how my Custom model looks like, just in case if you required

class AuthUser(AbstractUser):
    ADMIN = 'A'
    STUDENT = 'S'
    TUTOR = 'T'
    ROLE_CHOICES = (
        (ADMIN, 'Superuser'),
        (STUDENT, 'Student'),
        (TUTOR, 'Tutor'),
    )
    username = None
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(max_length=254, unique=True)
    role = models.CharField(max_length=1, choices=ROLE_CHOICES, default=STUDENT)
    password = models.CharField(max_length=128)
    is_active = models.BooleanField(default=True)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['password']
    objects = UserManager()

    def __str__(self):
        return self.email
    
    def has_perm(self, perm, obj=None):
        return True
    
    def has_module_perms(self, app_label):
        return True
    
    def __str__(self):
        return self.email

Hey there!
Take a look into limit_choices_to

1 Like