views:

863

answers:

2

I'm using the row-level permission model known as django-granular-permissions (http://code.google.com/p/django-granular-permissions/). The permission model simply has just two more fields which are content-type and object id.

I've used the following query:

 User.objects.filter(Q(row_permission_set__name='staff') | \
     Q(row_permission_set__name='student'), \
     row_permission_set__object_id=labsite.id)

I want to add is_staff and is_student boolean fields to the result set without querying everytime when I fetch the result.

Django documentation shows extra() method of querysets, but I can't figure out what I should write for plain SQL selection query with this relation.

How to do this?

A: 

Normally you'd use select_related() for things like this, but unfortunately it doesn't work on reverse relationships. What you could do is turn the query around:

users = [permission.user for permission in Permission.objects.select_related('user').filter(...)]
oggy
In your query, how do I determine each user has some permission or not? (especially, in convenient form for templates)
Achimnol
Due to the filter on the Permission objects (you just filter out the desired permissions), all of your users in the list will have the desired permissions. If all you need to do is to display the users with the desired permissions, this is simpler than the .extra(). If you need to list *all* users and then do specific stuff for those who have some permissions, then extra() is the way to go.
oggy
+1  A: 
.extra(select={'is_staff': "%s.name='staff'" % Permission._meta.db_table, 'is_student': "%s.name='student'" % Permission._meta.db_table, })
Glader
It works pretty well. :)
Achimnol