amir_70
amir_70

Reputation: 930

how to access a field from a another in many to many relation?

I have two models "User" and "Role". Role model is like this:

 class Role(models.Model):
     ADMIN = 1
     INFORMATIC = 2
     REFEREE = 3
     SPONSER = 4
     STAFF = 5
     PLAYER = 6
     CUSTOMER =7
     VISITOR = 8

     ROLE_CHOICES = (
        (1, 'admin'),
        (2, 'informatic'),
        (3, 'referee'),
        (4, 'sponser'),
        (5, 'staff'),
        (6, 'player'),
        (7, 'customer'),
        (8, 'visitor'),
     )
     id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True , 
        default=VISITOR)

and here is my User model:

 class User(AbstractBaseUser,PermissionsMixin):
    username = models.CharField(max_length=150, unique=True, blank=True , null=True,)
    password = models.CharField(max_length=100, null=True , blank=True)

    roles = models.ManyToManyField(Role)

now I have created some Role objects and some Users and assigned some Roles to some Users. now I want to know how can I determine which user has which roles? from request I have the user. I want to know if a User has a role, for example, sponsor, and grants him some permissions. how can i check this ?

EDIT when i use usrobj.roles.filter() it returns something like this:

<QuerySet [<Role: (2, 'informatic')>, <Role: (3, 'referee')>]>

and using userobj.roles.filter(id=1) returns like this:

<QuerySet [<Role: (2, 'informatic')>]>

and obviously this is not what i want

Upvotes: 0

Views: 31

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599490

You can query the role directly and check .exists():

request.user.roles.filter(id=1).exists()

(Note, I really don't recommend using the ID as the choice in the Role model. Use a separate role field.)

Upvotes: 2

Sam Creamer
Sam Creamer

Reputation: 5361

For example, if you want to know if someone is an admin:

In a view:

admin_role = Role.objects.get(id=1)
admin_users = User.objects.filter(roles__in=admin_role)

# To check if a user is admin
if admin_role in user.roles.all():
    pass

Good luck!

Upvotes: 1

Related Questions