Is there a better solution to filter model objects by permission in django
I have a Django model Task containing permissions.
from django.db import models
from django.contrib.auth.models import Permission
# Other stuff
class TaskType(models.Model):
required_permissions = models.ManyToManyField(Permission)
# Other non relevant fields
class Task(models.Model):
begin = models.DateTimeField( #Options left out
end = models.DateTimeField( #Options left out
type = models.ForeignKey(TaskType, on_delete=models.CASCADE)
# Other non relevant fields
Now I have a view where a user is supposed to select a Task in a specific Time slot but should only choose from tasks where the user has the required permissions for and where the task in question wouldn't be blocked by another task in that time slot the user was already assigned to.
My current solution to this problem is to query objects from the objects from the database that could be a valid candidates and filter out the ones the user has no permission for in python. This obviously feels a bit silly since this should be done by the database query (as database management systems are quite sophisticated for such tasks). My current solution looks like this:
def is_task_valid(self, task):
for p in task.type.permissions.all():
if not user.has_perm(p.content_type.app_label + "." + p.codename):
return False:
# Also checks for all assigned tasks of user in that time slot and returns False
# if they overlap
return True
def get_context_data(self):
# obtains other data
for t in self.get_task_query_set()
if self.is_task_valid(t):
context["tasks"].append(t)
# ...
return context
Is there a better solution to this problem? Filtering for the permissions using the Django QuerySet API troubles me quite a bit.