djangodjango-permissionsdjango-guardian

Row based permissions in Django


I have a simple Django model which looks roughly like this:

from django.contrib.auth.models import Group
from mylogapp.models import LogType

class Log(models.Model):
    responsible_group = models.ForeignKey(Group)
    description = models.TextField()
    log_type = models.ForeignKey(LogType)

There will be several million rows in the database table.

Row based permission for the django admin interface should get implemented.

If the current user is in the "responsible_group", then he is allowed to see and modify it.

AFAIK django guardian is not well suited for this. See this related page: https://django-guardian.readthedocs.io/en/stable/userguide/performance.html

Even solution "Direct foreign keys" does not match. The current model already contains everything which is needed to filter the rows.

How to enable row-based-permission for django and use the Log model for permission checking?


Solution

  • does using get_queryset() help?

    class LogAdmin(admin.ModelAdmin):
        def get_queryset(self, request):
            qs = super().get_queryset(request)
            return qs.filter(responsible_group__in=request.user.groups.all())