jeudi 5 août 2021

Django Models Relationship and Creation Flow - How to link all models to the user's parent

I’me new to software development, and I'm struggling with a basic design problem.

I’m building a SaaS platform where the user Admin signs up and creates and Organization. Every user should belong to an organization. The user can add abstract users Workers and Hubs, and every worker belongs to a hub. Any model that is created should belong to an organization. I’m trying to figure out the best practice to associate all the models to their respective organizations and how the signup flow should be with both Admin and Organization. Should I create the user first or the organization? Does it matter?

Also I'm a bit confused on how to use created_by.organization or request.user.organization to assign the created Worker to the creator's organization in the worker creation form (the same concept will apply to all other forms).

User Model

class CustomUser(AbstractUser):

    ...
    organization = models.ForeignKey(
        Organization, on_delete=models.CASCADE, related_name="organization", null=False)
    ...
 

Organization Model

class Organization(TimeStampedModel):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200, blank=False,
                            validators=[MinLengthValidator(3)])
    email = models.EmailField(max_length=70, blank=False, unique=True, validators=[
                              MinLengthValidator(3)])
    image = models.ImageField(
        upload_to='organizations-images/', blank=True, null=True)
    timezone = TimeZoneField(default='Europe/London',
                             choices_display='WITH_GMT_OFFSET')

    def __str__(self):
        return self.name

Worker Model

class Worker(CustomUser, TimeStampedModel):

    hub = models.ForeignKey(
        Hub,
        on_delete=models.RESTRICT, related_name='hub_workers'
    )
    def __str__(self):
        return self.display_name

Hub Model

class Hub(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    organization = models.ForeignKey(
        Organization,
        on_delete=models.RESTRICT, related_name='organization_hubs',
    )
    name = models.CharField(max_length=200, blank=False,
                            unique=True)
    address = models.ForeignKey(
        Address,
        on_delete=models.RESTRICT, related_name='hub_address'
    )

    def __str__(self):
        return self.name

Note: probably I should remove organization from hub and link it through its creator's organization.

Create Worker Form

class WorkerCreateForm(forms.ModelForm):

    class Meta:
        model = Worker
        fields = '__all__'

I want to make sure that whenever a form is submitted, the newly created model should belong to its creator's organization.

Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire