We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] Docker 1.13-dev: Multi-User Setup, can't change anything with to document details
### Description

Hi, I am pretty new to paperless. I wanted to start directly with the multi-user feature for my whole family. So I decided to install the dev-docker image. It runs quote nice, there is just this one thing...
When a document has permission set to owner: Person A and read permission to Person B. I cannot change anything within the document e.g. Name, Permission, Tags, Document type etc.

When I try to do so, there is just this error:
`Error saving document: Http failure response for https://example.com/api/documents/23/: 500 OK`

The change thru the webui won't be saved. When I remove the permission (read-permission to Person B) everything is working thru the webui. When I put the permission back, the error comes back as well.

BTW I can change things without a problem within the Django admin panel.

### Steps to reproduce

1. Have a document
2. Have different users
3. Share this document as an owner to a second person
4. Error pops up when trying to change information on the document
5. remove permission, leave owner
6. Document can be changed
7. give read permission to the second person again
8. same error comes back

### Webserver logs

```bash
[2023-03-31 22:13:36,819] [ERROR] [django.request] Internal Server Error: /api/documents/23/
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/asgiref/sync.py", line 486, in thread_handler
    raise exc_info[1]
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 43, in inner
    response = await get_response(request)
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 253, in _get_response_async
    response = await wrapped_callback(
  File "/usr/local/lib/python3.9/site-packages/asgiref/sync.py", line 448, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "/usr/local/lib/python3.9/asyncio/tasks.py", line 442, in wait_for
    return await fut
  File "/usr/local/lib/python3.9/site-packages/asgiref/current_thread_executor.py", line 22, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.9/site-packages/asgiref/sync.py", line 490, in thread_handler
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 55, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/src/paperless/src/documents/views.py", line 278, in update
    response = super().update(request, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 68, in update
    self.perform_update(serializer)
  File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 78, in perform_update
    serializer.save()
  File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 207, in save
    self.instance = self.update(self.instance, validated_data)
  File "/usr/src/paperless/src/documents/serialisers.py", line 419, in update
    super().update(instance, validated_data)
  File "/usr/src/paperless/src/documents/serialisers.py", line 210, in update
    self._set_permissions(validated_data["set_permissions"], instance)
  File "/usr/src/paperless/src/documents/serialisers.py", line 149, in _set_permissions
    set_permissions_for_object(permissions, object)
  File "/usr/src/paperless/src/documents/permissions.py", line 70, in set_permissions_for_object
    if len(users_to_remove) > 0:
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 376, in __len__
    self._fetch_all()
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1867, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 87, in __iter__
    results = compiler.execute_sql(
  File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1385, in execute_sql
    sql, params = self.as_sql()
  File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 603, in as_sql
    raise NotSupportedError(
django.db.utils.NotSupportedError: difference is not supported on this database backend.
```


### Browser logs

_No response_

### Paperless-ngx version

1.13.0-dev

### Host OS

Docker@Ubuntu 22.04

### Installation method

Docker - official image

### Browser

Safari

### Configuration changes

_No response_

### Other

_No response_

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/documents/permissions.py`
Content:
```
1 from django.contrib.auth.models import Group
2 from django.contrib.auth.models import Permission
3 from django.contrib.auth.models import User
4 from django.contrib.contenttypes.models import ContentType
5 from guardian.models import GroupObjectPermission
6 from guardian.shortcuts import assign_perm
7 from guardian.shortcuts import get_users_with_perms
8 from guardian.shortcuts import remove_perm
9 from rest_framework.permissions import BasePermission
10 from rest_framework.permissions import DjangoObjectPermissions
11 
12 
13 class PaperlessObjectPermissions(DjangoObjectPermissions):
14     """
15     A permissions backend that checks for object-level permissions
16     or for ownership.
17     """
18 
19     perms_map = {
20         "GET": ["%(app_label)s.view_%(model_name)s"],
21         "OPTIONS": ["%(app_label)s.view_%(model_name)s"],
22         "HEAD": ["%(app_label)s.view_%(model_name)s"],
23         "POST": ["%(app_label)s.add_%(model_name)s"],
24         "PUT": ["%(app_label)s.change_%(model_name)s"],
25         "PATCH": ["%(app_label)s.change_%(model_name)s"],
26         "DELETE": ["%(app_label)s.delete_%(model_name)s"],
27     }
28 
29     def has_object_permission(self, request, view, obj):
30         if hasattr(obj, "owner") and obj.owner is not None:
31             if request.user == obj.owner:
32                 return True
33             else:
34                 return super().has_object_permission(request, view, obj)
35         else:
36             return True  # no owner
37 
38 
39 class PaperlessAdminPermissions(BasePermission):
40     def has_permission(self, request, view):
41         return request.user.has_perm("admin.view_logentry")
42 
43 
44 def get_groups_with_only_permission(obj, codename):
45     ctype = ContentType.objects.get_for_model(obj)
46     permission = Permission.objects.get(content_type=ctype, codename=codename)
47     group_object_perm_group_ids = (
48         GroupObjectPermission.objects.filter(
49             object_pk=obj.pk,
50             content_type=ctype,
51         )
52         .filter(permission=permission)
53         .values_list("group_id")
54     )
55     return Group.objects.filter(id__in=group_object_perm_group_ids).distinct()
56 
57 
58 def set_permissions_for_object(permissions, object):
59     for action in permissions:
60         permission = f"{action}_{object.__class__.__name__.lower()}"
61         # users
62         users_to_add = User.objects.filter(id__in=permissions[action]["users"])
63         users_to_remove = get_users_with_perms(
64             object,
65             only_with_perms_in=[permission],
66             with_group_users=False,
67         )
68         if len(users_to_add) > 0 and len(users_to_remove) > 0:
69             users_to_remove = users_to_remove.difference(users_to_add)
70         if len(users_to_remove) > 0:
71             for user in users_to_remove:
72                 remove_perm(permission, user, object)
73         if len(users_to_add) > 0:
74             for user in users_to_add:
75                 assign_perm(permission, user, object)
76                 if action == "change":
77                     # change gives view too
78                     assign_perm(
79                         f"view_{object.__class__.__name__.lower()}",
80                         user,
81                         object,
82                     )
83         # groups
84         groups_to_add = Group.objects.filter(id__in=permissions[action]["groups"])
85         groups_to_remove = get_groups_with_only_permission(
86             object,
87             permission,
88         )
89         if len(groups_to_add) > 0 and len(groups_to_remove) > 0:
90             groups_to_remove = groups_to_remove.difference(groups_to_add)
91         if len(groups_to_remove) > 0:
92             for group in groups_to_remove:
93                 remove_perm(permission, group, object)
94         if len(groups_to_add) > 0:
95             for group in groups_to_add:
96                 assign_perm(permission, group, object)
97                 if action == "change":
98                     # change gives view too
99                     assign_perm(
100                         f"view_{object.__class__.__name__.lower()}",
101                         group,
102                         object,
103                     )
104
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/documents/permissions.py b/src/documents/permissions.py
--- a/src/documents/permissions.py
+++ b/src/documents/permissions.py
@@ -66,7 +66,7 @@
             with_group_users=False,
         )
         if len(users_to_add) > 0 and len(users_to_remove) > 0:
-            users_to_remove = users_to_remove.difference(users_to_add)
+            users_to_remove = users_to_remove.exclude(id__in=users_to_add)
         if len(users_to_remove) > 0:
             for user in users_to_remove:
                 remove_perm(permission, user, object)
@@ -87,7 +87,7 @@
             permission,
         )
         if len(groups_to_add) > 0 and len(groups_to_remove) > 0:
-            groups_to_remove = groups_to_remove.difference(groups_to_add)
+            groups_to_remove = groups_to_remove.exclude(id__in=groups_to_add)
         if len(groups_to_remove) > 0:
             for group in groups_to_remove:
                 remove_perm(permission, group, object)

{"golden_diff": "diff --git a/src/documents/permissions.py b/src/documents/permissions.py\n--- a/src/documents/permissions.py\n+++ b/src/documents/permissions.py\n@@ -66,7 +66,7 @@\n             with_group_users=False,\n         )\n         if len(users_to_add) > 0 and len(users_to_remove) > 0:\n-            users_to_remove = users_to_remove.difference(users_to_add)\n+            users_to_remove = users_to_remove.exclude(id__in=users_to_add)\n         if len(users_to_remove) > 0:\n             for user in users_to_remove:\n                 remove_perm(permission, user, object)\n@@ -87,7 +87,7 @@\n             permission,\n         )\n         if len(groups_to_add) > 0 and len(groups_to_remove) > 0:\n-            groups_to_remove = groups_to_remove.difference(groups_to_add)\n+            groups_to_remove = groups_to_remove.exclude(id__in=groups_to_add)\n         if len(groups_to_remove) > 0:\n             for group in groups_to_remove:\n                 remove_perm(permission, group, object)\n", "issue": "[BUG] Docker 1.13-dev: Multi-User Setup, can't change anything with to document details\n### Description\n\nHi, I am pretty new to paperless. I wanted to start directly with the multi-user feature for my whole family. So I decided to install the dev-docker image. It runs quote nice, there is just this one thing...\r\nWhen a document has permission set to owner: Person A and read permission to Person B. I cannot change anything within the document e.g. Name, Permission, Tags, Document type etc.\r\n\r\nWhen I try to do so, there is just this error:\r\n`Error saving document: Http failure response for https://example.com/api/documents/23/: 500 OK`\r\n\r\nThe change thru the webui won't be saved. When I remove the permission (read-permission to Person B) everything is working thru the webui. When I put the permission back, the error comes back as well.\r\n\r\nBTW I can change things without a problem within the Django admin panel.\n\n### Steps to reproduce\n\n1. Have a document\r\n2. Have different users\r\n3. Share this document as an owner to a second person\r\n4. Error pops up when trying to change information on the document\r\n5. remove permission, leave owner\r\n6. Document can be changed\r\n7. give read permission to the second person again\r\n8. same error comes back\n\n### Webserver logs\n\n```bash\n[2023-03-31 22:13:36,819] [ERROR] [django.request] Internal Server Error: /api/documents/23/\r\nTraceback (most recent call last):\r\n  File \"/usr/local/lib/python3.9/site-packages/asgiref/sync.py\", line 486, in thread_handler\r\n    raise exc_info[1]\r\n  File \"/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 43, in inner\r\n    response = await get_response(request)\r\n  File \"/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py\", line 253, in _get_response_async\r\n    response = await wrapped_callback(\r\n  File \"/usr/local/lib/python3.9/site-packages/asgiref/sync.py\", line 448, in __call__\r\n    ret = await asyncio.wait_for(future, timeout=None)\r\n  File \"/usr/local/lib/python3.9/asyncio/tasks.py\", line 442, in wait_for\r\n    return await fut\r\n  File \"/usr/local/lib/python3.9/site-packages/asgiref/current_thread_executor.py\", line 22, in run\r\n    result = self.fn(*self.args, **self.kwargs)\r\n  File \"/usr/local/lib/python3.9/site-packages/asgiref/sync.py\", line 490, in thread_handler\r\n    return func(*args, **kwargs)\r\n  File \"/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py\", line 55, in wrapped_view\r\n    return view_func(*args, **kwargs)\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/viewsets.py\", line 125, in view\r\n    return self.dispatch(request, *args, **kwargs)\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/views.py\", line 509, in dispatch\r\n    response = self.handle_exception(exc)\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/views.py\", line 469, in handle_exception\r\n    self.raise_uncaught_exception(exc)\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/views.py\", line 480, in raise_uncaught_exception\r\n    raise exc\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/views.py\", line 506, in dispatch\r\n    response = handler(request, *args, **kwargs)\r\n  File \"/usr/src/paperless/src/documents/views.py\", line 278, in update\r\n    response = super().update(request, *args, **kwargs)\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py\", line 68, in update\r\n    self.perform_update(serializer)\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py\", line 78, in perform_update\r\n    serializer.save()\r\n  File \"/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py\", line 207, in save\r\n    self.instance = self.update(self.instance, validated_data)\r\n  File \"/usr/src/paperless/src/documents/serialisers.py\", line 419, in update\r\n    super().update(instance, validated_data)\r\n  File \"/usr/src/paperless/src/documents/serialisers.py\", line 210, in update\r\n    self._set_permissions(validated_data[\"set_permissions\"], instance)\r\n  File \"/usr/src/paperless/src/documents/serialisers.py\", line 149, in _set_permissions\r\n    set_permissions_for_object(permissions, object)\r\n  File \"/usr/src/paperless/src/documents/permissions.py\", line 70, in set_permissions_for_object\r\n    if len(users_to_remove) > 0:\r\n  File \"/usr/local/lib/python3.9/site-packages/django/db/models/query.py\", line 376, in __len__\r\n    self._fetch_all()\r\n  File \"/usr/local/lib/python3.9/site-packages/django/db/models/query.py\", line 1867, in _fetch_all\r\n    self._result_cache = list(self._iterable_class(self))\r\n  File \"/usr/local/lib/python3.9/site-packages/django/db/models/query.py\", line 87, in __iter__\r\n    results = compiler.execute_sql(\r\n  File \"/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py\", line 1385, in execute_sql\r\n    sql, params = self.as_sql()\r\n  File \"/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py\", line 603, in as_sql\r\n    raise NotSupportedError(\r\ndjango.db.utils.NotSupportedError: difference is not supported on this database backend.\n```\n\n\n### Browser logs\n\n_No response_\n\n### Paperless-ngx version\n\n1.13.0-dev\n\n### Host OS\n\nDocker@Ubuntu 22.04\n\n### Installation method\n\nDocker - official image\n\n### Browser\n\nSafari\n\n### Configuration changes\n\n_No response_\n\n### Other\n\n_No response_\n", "before_files": [{"content": "from django.contrib.auth.models import Group\nfrom django.contrib.auth.models import Permission\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom guardian.models import GroupObjectPermission\nfrom guardian.shortcuts import assign_perm\nfrom guardian.shortcuts import get_users_with_perms\nfrom guardian.shortcuts import remove_perm\nfrom rest_framework.permissions import BasePermission\nfrom rest_framework.permissions import DjangoObjectPermissions\n\n\nclass PaperlessObjectPermissions(DjangoObjectPermissions):\n    \"\"\"\n    A permissions backend that checks for object-level permissions\n    or for ownership.\n    \"\"\"\n\n    perms_map = {\n        \"GET\": [\"%(app_label)s.view_%(model_name)s\"],\n        \"OPTIONS\": [\"%(app_label)s.view_%(model_name)s\"],\n        \"HEAD\": [\"%(app_label)s.view_%(model_name)s\"],\n        \"POST\": [\"%(app_label)s.add_%(model_name)s\"],\n        \"PUT\": [\"%(app_label)s.change_%(model_name)s\"],\n        \"PATCH\": [\"%(app_label)s.change_%(model_name)s\"],\n        \"DELETE\": [\"%(app_label)s.delete_%(model_name)s\"],\n    }\n\n    def has_object_permission(self, request, view, obj):\n        if hasattr(obj, \"owner\") and obj.owner is not None:\n            if request.user == obj.owner:\n                return True\n            else:\n                return super().has_object_permission(request, view, obj)\n        else:\n            return True  # no owner\n\n\nclass PaperlessAdminPermissions(BasePermission):\n    def has_permission(self, request, view):\n        return request.user.has_perm(\"admin.view_logentry\")\n\n\ndef get_groups_with_only_permission(obj, codename):\n    ctype = ContentType.objects.get_for_model(obj)\n    permission = Permission.objects.get(content_type=ctype, codename=codename)\n    group_object_perm_group_ids = (\n        GroupObjectPermission.objects.filter(\n            object_pk=obj.pk,\n            content_type=ctype,\n        )\n        .filter(permission=permission)\n        .values_list(\"group_id\")\n    )\n    return Group.objects.filter(id__in=group_object_perm_group_ids).distinct()\n\n\ndef set_permissions_for_object(permissions, object):\n    for action in permissions:\n        permission = f\"{action}_{object.__class__.__name__.lower()}\"\n        # users\n        users_to_add = User.objects.filter(id__in=permissions[action][\"users\"])\n        users_to_remove = get_users_with_perms(\n            object,\n            only_with_perms_in=[permission],\n            with_group_users=False,\n        )\n        if len(users_to_add) > 0 and len(users_to_remove) > 0:\n            users_to_remove = users_to_remove.difference(users_to_add)\n        if len(users_to_remove) > 0:\n            for user in users_to_remove:\n                remove_perm(permission, user, object)\n        if len(users_to_add) > 0:\n            for user in users_to_add:\n                assign_perm(permission, user, object)\n                if action == \"change\":\n                    # change gives view too\n                    assign_perm(\n                        f\"view_{object.__class__.__name__.lower()}\",\n                        user,\n                        object,\n                    )\n        # groups\n        groups_to_add = Group.objects.filter(id__in=permissions[action][\"groups\"])\n        groups_to_remove = get_groups_with_only_permission(\n            object,\n            permission,\n        )\n        if len(groups_to_add) > 0 and len(groups_to_remove) > 0:\n            groups_to_remove = groups_to_remove.difference(groups_to_add)\n        if len(groups_to_remove) > 0:\n            for group in groups_to_remove:\n                remove_perm(permission, group, object)\n        if len(groups_to_add) > 0:\n            for group in groups_to_add:\n                assign_perm(permission, group, object)\n                if action == \"change\":\n                    # change gives view too\n                    assign_perm(\n                        f\"view_{object.__class__.__name__.lower()}\",\n                        group,\n                        object,\n                    )\n", "path": "src/documents/permissions.py"}], "after_files": [{"content": "from django.contrib.auth.models import Group\nfrom django.contrib.auth.models import Permission\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom guardian.models import GroupObjectPermission\nfrom guardian.shortcuts import assign_perm\nfrom guardian.shortcuts import get_users_with_perms\nfrom guardian.shortcuts import remove_perm\nfrom rest_framework.permissions import BasePermission\nfrom rest_framework.permissions import DjangoObjectPermissions\n\n\nclass PaperlessObjectPermissions(DjangoObjectPermissions):\n    \"\"\"\n    A permissions backend that checks for object-level permissions\n    or for ownership.\n    \"\"\"\n\n    perms_map = {\n        \"GET\": [\"%(app_label)s.view_%(model_name)s\"],\n        \"OPTIONS\": [\"%(app_label)s.view_%(model_name)s\"],\n        \"HEAD\": [\"%(app_label)s.view_%(model_name)s\"],\n        \"POST\": [\"%(app_label)s.add_%(model_name)s\"],\n        \"PUT\": [\"%(app_label)s.change_%(model_name)s\"],\n        \"PATCH\": [\"%(app_label)s.change_%(model_name)s\"],\n        \"DELETE\": [\"%(app_label)s.delete_%(model_name)s\"],\n    }\n\n    def has_object_permission(self, request, view, obj):\n        if hasattr(obj, \"owner\") and obj.owner is not None:\n            if request.user == obj.owner:\n                return True\n            else:\n                return super().has_object_permission(request, view, obj)\n        else:\n            return True  # no owner\n\n\nclass PaperlessAdminPermissions(BasePermission):\n    def has_permission(self, request, view):\n        return request.user.has_perm(\"admin.view_logentry\")\n\n\ndef get_groups_with_only_permission(obj, codename):\n    ctype = ContentType.objects.get_for_model(obj)\n    permission = Permission.objects.get(content_type=ctype, codename=codename)\n    group_object_perm_group_ids = (\n        GroupObjectPermission.objects.filter(\n            object_pk=obj.pk,\n            content_type=ctype,\n        )\n        .filter(permission=permission)\n        .values_list(\"group_id\")\n    )\n    return Group.objects.filter(id__in=group_object_perm_group_ids).distinct()\n\n\ndef set_permissions_for_object(permissions, object):\n    for action in permissions:\n        permission = f\"{action}_{object.__class__.__name__.lower()}\"\n        # users\n        users_to_add = User.objects.filter(id__in=permissions[action][\"users\"])\n        users_to_remove = get_users_with_perms(\n            object,\n            only_with_perms_in=[permission],\n            with_group_users=False,\n        )\n        if len(users_to_add) > 0 and len(users_to_remove) > 0:\n            users_to_remove = users_to_remove.exclude(id__in=users_to_add)\n        if len(users_to_remove) > 0:\n            for user in users_to_remove:\n                remove_perm(permission, user, object)\n        if len(users_to_add) > 0:\n            for user in users_to_add:\n                assign_perm(permission, user, object)\n                if action == \"change\":\n                    # change gives view too\n                    assign_perm(\n                        f\"view_{object.__class__.__name__.lower()}\",\n                        user,\n                        object,\n                    )\n        # groups\n        groups_to_add = Group.objects.filter(id__in=permissions[action][\"groups\"])\n        groups_to_remove = get_groups_with_only_permission(\n            object,\n            permission,\n        )\n        if len(groups_to_add) > 0 and len(groups_to_remove) > 0:\n            groups_to_remove = groups_to_remove.exclude(id__in=groups_to_add)\n        if len(groups_to_remove) > 0:\n            for group in groups_to_remove:\n                remove_perm(permission, group, object)\n        if len(groups_to_add) > 0:\n            for group in groups_to_add:\n                assign_perm(permission, group, object)\n                if action == \"change\":\n                    # change gives view too\n                    assign_perm(\n                        f\"view_{object.__class__.__name__.lower()}\",\n                        group,\n                        object,\n                    )\n", "path": "src/documents/permissions.py"}]}