Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Simply do:</p> <pre><code>def has_roles(user, roles): return user.profile.user_types.filter(pk__in=roles).count() == len(roles) print has_roles(user, [6,7,8]) </code></pre> <p>P.S. I would shy away from using hard coded PK ID numbers as your identifiers. Too many things can go wrong with that. Instead define a mapping at runtime and reference them by names. Multiple things will improve:</p> <ul> <li>Your code will be much easier to read </li> <li>Django will offload model instance matching to the DB the first item</li> <li>From then on you can cache the ID and not ask the DB again</li> </ul> <p>Then you can do:</p> <pre><code>class UserType( models.Model ): TYPES = (( 'tenant', 'Tenant'), ( 'propman', 'Property Manager'), ( 'propown', 'Property Owner'), ( 'vendman', 'Vendor Manager'), ( 'vendor', 'Vendor'), ( 'viewer', 'Viewer'), ( 'moderator', 'Moderator'), ( 'admin', 'Administrator')) name = models.CharField( max_length = 135, choices=TYPES ) def has_role(user, role): return user.profile.user_types.filter(name=role).count() == 1 def has_roles(user, roles): return user.profile.user_types.filter(name__in=roles).count() == len(roles) print has_roles(user, ['viewer','moderator','admin']) </code></pre> <p>Finally, you can add the two functions above to:</p> <pre><code>class UserProfile( models.Model ) : user = models.OneToOneField( User ) user_types = models.ManyToManyField( UserType, null = True, blank = True ) def has_role(self, role): return self.user_types.filter(name=role).count() == 1 def has_roles(self, roles): return self.user_types.filter(name__in=roles).count() == len(roles) </code></pre> <p>And then use it like this in the future:</p> <pre><code>u = User.objects.get(username='me') if u.userprofile.has_role('admin'): print 'I have the powah!' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload