List objects based on permission
kirthiprakash opened this issue · 1 comments
kirthiprakash commented
Hi!
Is there an API to list objects based on the user permissions?
Currently I can do this.
[article for article in articles if user_obj.has_perm('view_article', article)]
But it will be better if I can query it at the db level.
Just checking if django-permissions has an API for this?
lambdalisue commented
No. django-permission have been developed as a non database based permission system.
So the way you showed me is the only way to do it BUT if you have tons of articles
, it will take long time to check if the user_obj
have a view_article
permission of each.
In my case, I usually add published
method to the manager. The method filter articles based on the logic used in permission logic:
class ArticleManager(models.Manager):
# filter articles by `is_public` which is used in permission logic.
def published(self, user):
if user.is_authenticated():
return self.all()
return self.filter(is_public=True)
class Article(models.Model):
is_public = models.BooleanField(...)
objects = ArticleManager()
# PermissionLogicClass which will be applied to Article
class ArticlePermissionLogic(PermissionLogic):
def has_perm(self, user_obj, perm, obj):
if perm == 'articles.view_article':
if not obj:
return True
return user_obj.is_authenticated()
return False