Search code examples
djangodjango-modelsrelational-databaseone-to-many

Django - One to Many relationship


I have user and user role models. There are 3 user roles as teacher, student, admin. One user should have only one role but if I make one-to-one relationship only one user can be attached to one role. I want there can be many students, many teacher, many admins but one user must only have one role. I couldn't figure out how to design this relationship.

I have 2 models as User and User_Role.

class role(models.Model):
   role_name = models.CharField(max_length=64)

class user(models.Model):
   name = models.CharField(max_length=64)

Solution

  • You should define a ForeignKey from the User model to the Role, so:

    class Role(models.Model):
        role_name = models.CharField(max_length=64)
    
    class User(models.Model):
        name = models.CharField(max_length=64)
        role = models.ForeignKey(Role, on_delete=models.PROTECT)

    Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from user to User.