Search code examples
djangodjango-models

Django user_auth how to foreign key one to many


What I'm looking for is that a many users can be part of a tenant, so my idea in the beginning was to foreign key from user to tenant but I can't found how to do this. This is what I have at the moment:

models.py

class Tenants(models.Model):
    empresa = models.CharField(max_length=60, null=False, blank=False)
    sub_dominio = models.CharField(max_length=60, null=True, blank=True)
    usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.CharField(max_length=20, null=False, blank=False)

    class Meta:
        verbose_name_plural = "Tenants"

    def __str__(self):
        return self.empresa

But with this solution I can only have a User per Tenant, how can I do Many users per tenant?


Solution

  • I understood that you are connecting multiple users to the tenants model. The foreign key must be generated by the user in reverse.

    tenants/models.py

    from django.db import models
    
    # Create your models here.
    class Tenants(models.Model):
        empresa = models.CharField(max_length=60, null=False, blank=False)
        sub_dominio = models.CharField(max_length=60, null=True, blank=True)
        updated_at = models.DateTimeField(auto_now=True)
        created_by = models.CharField(max_length=20, null=False, blank=False)
    
        class Meta:
            verbose_name_plural = "Tenants"
    
        def __str__(self):
            return self.empresa
    

    users/models.py

    from django.db import models
    from django.contrib.auth.base_user import AbstractBaseUser
    from django.contrib.auth.models import UserManager, PermissionsMixin
    from tenants.models import Tenants
    
    # Create your models here.
    
    
    class User(AbstractBaseUser, PermissionsMixin):
      
      objects = UserManager()
      
      username = models.CharField(
          max_length=150,
          unique=True,
      ) 
      email = models.EmailField(blank=True)
      is_staff = models.BooleanField(
        default=False,
      )
      is_active = models.BooleanField(
        default=True,
      )
    
      tenants = models.ForeignKey(Tenants, on_delete=models.SET_NULL, null=True, related_name='users')
      
      EMAIL_FIELD = "email"
      USERNAME_FIELD = "username"
      REQUIRED_FIELDS = ["email"]
      
      def __str__(self):
        return self.username