django-multitenant icon indicating copy to clipboard operation
django-multitenant copied to clipboard

RecursionError in __setattr__ when the tenant_field is not loaded initially.

Open wenzhiTeo opened this issue 5 months ago • 0 comments

The case: Run query with Django's only() and did not include the tenant_field in only fields, something like below:

bot= BotUser.objects.only("id").first()
django.core.serializers.serialize("json",[bot])

We will get the RecursionError: __setattr__ > refresh_from_db > __setattr__ > refresh_from_db > ........

The error details are as follows: __setattr__= django_multitenant.setattr

  1. When we try to access the field not included in only (e.g. name of BotUser), __setattr__ triggered to set result from DB
  2. When __setattr__ triggered, trigger is_val_equal_to_tenant but tenant_value not set/fetched yet
  3. __setattr__ triggered to set tenant_value result from DB
  4. When __setattr__ triggered, tenant_value not able to set, because of tenant_value not set/fetched yet (step 2)

I think the checking should not be run when tenant_field not set yet


Possible fix:

 def __setattr__(self, attrname, val):
        def is_val_equal_to_tenant(val):
            if self.tenant_field not in self.__dict__:
                return True #Skip check when `tenant_field` not set yet
            return......# remain unchanged
        .....# remain unchanged

For quick fix, just ensuring the tenant_field always set before accessing any fields

wenzhiTeo avatar Sep 06 '24 17:09 wenzhiTeo