citusdata / django-multitenant

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

How do I scope the tenants to User Model ??? #102

Closed finch-wren closed 2 years ago

finch-wren commented 3 years ago

I tried extending the User model with a OneToOne field (I have tried both django's and yours) but I keep getting the error that User model doesn't inherit from your TenantModel/Mixin?

class UsersExtended(models.Model/TenantModel): users = models.OneToOneField/TenantOneToOneField(Users,on_delete="") store = models.ForeignKey(Store) tenant_id = 'store_id'

I am thinking maybe I should let go of the tenant_id thing in this usersextended model but I really am not sure. How do I relate the current user to a tenant in my middleware if I have to let go of the tenant_id thing even if I can access it via reverse relating the store field. Im having doubts on my practice. What is the correct way to scope Users to a Tenant(Store)???

Any help would be highly appreciated!!! Thank you

aecdanjun commented 3 years ago

I have the same question...

mrhaydari commented 2 years ago

If I'm not mistaken,u must create a custom auth model like this models.py

class CustomUser(AbstractUser, TenantModel):
    tenant_id = "id"
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="custom_user_set",
        related_query_name="custom_user",
    )
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name="custom_user_set",
        related_query_name="custom_user",
    )

setting.py

AUTH_USER_MODEL = "appname.CustomUser"

for relation keys

from django.conf import settings
user = models.ForeigenKey(settings.AUTH_USER_MODEL,...)

anywhere u want to get and use User object

from django.contrib.auth import get_user_model
User = get_user_model()
users = User.objects.filter()