简体   繁体   中英

Return QuerySet based on User group/permissions

I'm trying to figure out what's the "best practice" to limit QuerySet s based on User s 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM