Home > Software design >  Best approach to assigning existing data to a new django user
Best approach to assigning existing data to a new django user

Time:10-21

I am new in Django and I wanted to know what is the right approach to the following problem:

I have a table of companies, which is m2m with the table of users. Since they can be created by the users.
So what I want to do is, every time a user is created, I take a "default" company with a certain id and copy it to this new user.
This way the user will be able to make the changes he wants in this company without affecting the original one that is being copied.

CodePudding user response:

This should work:

def create_default_company_for_user(user: User):
    create_kwargs = {}  # Whatever values you want for the new company fields
    default_company = Company.objects.create(**create_kwargs)
    user.company_set.add(default_company)

Call this where you create users. The best way would probably be to use it as a Django's post_save signal receiver:

@receiver(post_save, sender=User)
def create_default_company_for_user(
    sender, user: User, created: bool, **kwargs
):
    if created:
        create_kwargs = {}  # Whatever values you want for the new company fields
        default_company = Company.objects.create(**create_kwargs)
        user.company_set.add(default_company)

Note: I haven't use a "default company to copy" what you want are default field values you can use to create new companies (in this case it's the create_kwargs variable, which should be a constant defined as a dictionary somewhere in your code)

  • Related