many to many relationship in django database model

Viewed 1975

Hi I am completely new to python and implementing ORM for first time in mysql.

we have three two tables and one intermediary table as shown in below diagram many to many relationship

below is the code we are using to create models

class Roles(models.Model):
    """
    A class that stores all the types of roles that are available to the user
    """
    role_id = models.CharField(max_length=200, blank=False,primary_key=True)
    role_name = models.CharField(max_length=200)

    class Meta:
        db_table = 'roles'
        managed = False


class User(AbstractBaseUser):
# class ChannelUser(models.Model):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    """
    user_id = models.CharField(max_length=200, blank=False,primary_key=True)
    user_email = models.EmailField(max_length=200, blank=False, unique=True)
    roles=models.ManyToManyField(
        Roles,
        through='UserRole',
        # through_fields=('user_id', 'role_id'),
    )

    USERNAME_FIELD = 'user_email'

    class Meta:
        db_table = 'user'
        managed = False

class UserRole(models.Model):
    """
    A class that stores user ids and role ids
    """
    user = models.ForeignKey(User, on_delete=models.PROTECT, db_column='user_id')
    role = models.ForeignKey(Roles, on_delete=models.PROTECT, db_column='role_id') 
    timestamp = models.DateTimeField(default=timezone.now)   

    class Meta:
        db_table = 'user_roles'
        managed = False

We are trying to fetch all the Roles associated with User, but it gives None for roles.

I am not sure, what we are doing wrong here. can somebody please point it out.

Below is the code I am using to fetch roles

user_detail = User.objects.get(user_email=username)
print(user_detail.user_email)  //prints user email
print(user_detail.roles) // prints Roles.None

settings.py

AUTH_USER_MODEL = "login_api.User"
1 Answers
Related