citusdata / django-multitenant

Python/Django support for distributed multi-tenant databases like Postgres+Citus
MIT License
710 stars 116 forks source link

`prefetch_related()` does not filter on the tenant field #122

Open pbav opened 2 years ago

pbav commented 2 years ago

The WHERE clause generated is just likeWHERE id IN (...)

prefetch_related with the Prefetch object works:

prefetch_related(
  Prefetch('field', Model.objects.all())
)

This workaround sometimes helps, but, for example, it does not work with @django-auto-prefetch

P.S. select_related works as expected, it does filter by tenant.

JelteF commented 2 years ago

Feel free to make a PR

pbav commented 2 years ago

This does the trick:

from django_multitenant.models import TenantModel as TenantModelBase

class TenantModel(TenantModelBase):
    class Meta:
        abstract = True

        # Access to related objects (specifically in prefetch_related) must use the tenant filter
        base_manager_name = 'objects'
        default_manager_name = 'objects'