Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue in is_val_equal_to_tenant leading to redundant DB calls #215

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions django_multitenant/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from django.db.models.sql import DeleteQuery, UpdateQuery
from django.db.models.deletion import Collector
from django.db.models import Model as DjangoModel
from django.db.utils import NotSupportedError
from django.conf import settings

Expand Down Expand Up @@ -126,12 +127,13 @@ def __setattr__(self, attrname, val):
# Provides failing of the save operation if the tenant_id is changed.
# try_update_tenant is being checked inside save method and if it is true, it will raise an exception.
def is_val_equal_to_tenant(val):
return (
val
and self.tenant_value
and val != self.tenant_value
and val != self.tenant_object
)
is_equal = val and self.tenant_value and val != self.tenant_value

if is_equal and isinstance(val, DjangoModel):
field = get_tenant_field(val)
is_equal = getattr(val, field.name) != self.tenant_value

return is_equal

if (
attrname in (self.tenant_field, get_tenant_field(self).name)
Expand Down
9 changes: 9 additions & 0 deletions django_multitenant/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,15 @@ def test_filter_select_related_not_id_field(self):
in captured_queries.captured_queries[0]["sql"]
)

def test_related_manager_query(self):
from .models import Project

account = self.account_fr
Project.objects.create(account=account, name=f"test_project")

with self.assertNumQueries(1):
list(account.projects.all())

def test_prefetch_related(self):
from .models import Project

Expand Down