Home > Mobile >  Django many-to-one relation with 3 tables
Django many-to-one relation with 3 tables

Time:09-21

I dont want any foreign keys directly in my users table, and by default, when I add a foreing key field in my custom User model, Django generate 2 tabels like this:

enter image description here

When I add a many-to-many field in my Company model I get the 3 desired tables but it's made possible for the same user be in two different companys.

class Company(models.Model):

    class Meta:
        verbose_name = 'Company'
        verbose_name_plural = 'Companys'
        ordering = ['name']
        db_table = 'companys'

    id      = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa')
    name    = models.CharField(max_length=100, verbose_name='Nome')
    users   = models.ManyToManyField(User, related_name='company', verbose_name='Users')

    def __str__(self):
        return self.name

I want Django to generate an additional table with only the Foreing Keys of the two models but keep the behevior of a many-to-one relationship between the two. like this:

enter image description here

CodePudding user response:

you can make your third table by using a separate model

class Company(models.Model):
    
    class Meta:
        verbose_name = 'Company'
        verbose_name_plural = 'Companys'
        ordering = ['name']
        db_table = 'companys'
    
    id      = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa')
    name    = models.CharField(max_length=100, verbose_name='Nome')
    
    def __str__(self):
        return self.name
class UserCompanyRelationModel(models.Model):
    
    class Meta:
        db_table = 'usr_comp'
    
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
  • Related