0

I have 2 models Account and User. An Account can have multiple users.

When the first User(Owner) is created at the same time the Account will be created.

Because User have a ForeignKey to Account, I need first to create the Account, and after the User.

But Account had a field created_by which is request.user. So is a circular problem.

I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user.

class Account(MetaData):
    name = models.CharField(max_length=255)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)

class User(AbstractBaseUser):
    account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner')

How can I do that ?

I need this only first time, for the first user, because after that for the other users the Account will exist.

When I'm saying first user, I'm not referring to staff users (as superusers), but normal users for which an account is mandatory thru a register form.

blank=True is just for staff members.

1
  • 1
    just a note, not a solution: in the code above, account field on User model is pointing to User (not Account) assuming AUTH_USER_MODEL is User. Commented Dec 7, 2017 at 11:56

2 Answers 2

2

Your User model's account field allows nulls, so nothing prevents you from first creating the user without an account, then creating the account with this user, and finally updating the user with the account:

 with transaction.atomic():
     user = User.objects.create(account=None, ...)
     account = Account.objects.create("test", created_by=user)
     user.account = account
     user.save(update_fields=["account"])
Sign up to request clarification or add additional context in comments.

Comments

0

Since it's only a problem for the first user, you might want to override the method create_superuser of the manager to add the account. Also, since you've defined the ForeignKeys with null=True, it should not be a problem to first create a superuser (using super().create_superuser()) and then create the account and attach it to the superuser.

When deploying your site the first time, you'll have to manually run the ./manage.py createsuperuser command.

2 Comments

when I'm saying first user, I'm not referring to staff users (as superusers), but normal users for which an account is mandatory
ah ok, that wasn't clear. Then the other answer fits the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.