﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35792	Enhance _get_group_permissions method of ModelBackend	Bona Fide IT GmbH	Bona Fide IT GmbH	"We would like to suggest a change to the `_get_group_permissions` method in the django `ModelBackend`.

The current code gets the registered `User` model and from it the `groups` field to get the related query name to compose a filter query for the `Permission` model at the end. 

{{{#!div style=""font-size: 80%""
Current version of `django/contrib/auth/backends.py` (https://github.com/django/django/blob/main/django/contrib/auth/backends.py#L61-L64) :
  {{{#!python
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.db.models import Exists, OuterRef, Q


UserModel = get_user_model()

...

class ModelBackend(BaseBackend):
      ...

      def _get_group_permissions(self, user_obj):
        user_groups_field = get_user_model()._meta.get_field(""groups"")
        user_groups_query = ""group__%s"" % user_groups_field.related_query_name()
        return Permission.objects.filter(**{user_groups_query: user_obj})

      ...
  }}}
}}}



Since in this method both the `group` field of the `Permission` model and the reverse relation field `groups` of the [custom] `User` model are fixed anyway, we suggest the following change.  

{{{#!div style=""font-size: 80%""
  {{{#!python
class ModelBackend(BaseBackend):
      ...

      def _get_group_permissions(self, user_obj):
        return Permission.objects.filter(group__in=user_obj.groups.all())

      ...
  }}}
}}}


We are not sure if this will fundamentally change the performance of the query, but it seems to us to be a simpler variant than going via `_meta` and then constructing a query string that is fixed anyway.

A further argument from our side is that this would probably also make it possible to use a custom `Group` model and to solve problems such as those mentioned here: https://github.com/django-guardian/django-guardian/pull/504#issuecomment-429810401 without introducing something like an `AUTH_GROUP_MODEL` setting."	Cleanup/optimization	closed	contrib.auth	4.2	Normal	fixed	Backend	Bona Fide IT GmbH	Ready for checkin	1	0	0	0	0	0
