Return QuerySet based on User group/permissions

453 Views Asked by At

I'm trying to figure out what's the "best practice" to limit QuerySets based on Users permissions.

For example, there is a table of invoices on the dashboard. User that has Group called Admin can see all invoices but User that has group Broker can see only their own invoices. That means only invoices that have user = ....

My idea is to create two permissions can_see_all_invoices and can_see_own_invoices.

Now when I call the QuerySet using Django Rest Framework, I'll check for the permissions and return the filtered QuerySet.

Or should I filter the QuerySet on the frontend and if Broker asks for all invoices I would raise PermissionError?

Which of these approaches are being used or is there a different approach?

1

There are 1 best solutions below

0
On

IMO, this would be a clean method

class MyInvoiceAPI:
    def get_queryset(self):
        qs = Invoice.objects.all()
        if self.request.user.has_perm('can_see_all_invoices'):
            return qs
        return qs.filter(user=self.request.user)

Notes

  • You don't need two permissions, only one which is can_see_all_invoices
  • I wouldn't raise any permission denied errors in this case, since it a List API, and evaluation of object is an expensive process