1

Let's say you have a ForeignKey MyModel.related_model and this related_model has all fields either null=True or default=something.

Like User.userprofile which I use on several places in my project. Is it better to create it immediately after User has been created?

either this way:

def save(...
    super().save(...
    UserProfile.objects.create(user=self)

or this:

@receiver(post_save...
def create_userprofile(...
    UserProfile.objects.get_or_create(user=self)

or should I create it when User first time goes to "Update profile" page?

Is there a pattern for that (excluding some special situations)?

0

In Django, ForeignKey fields are not optional by default, so unless UserProfile is a field that should ultimately only sometimes exist on the User, it's best to create and assign it immediately, before you save the newly created User. You shouldn't make UserProfile an optional ForeignKey unless it may never get created and remain unset indefinitely. Having optional fields that are always guaranteed to exist when needed would be a confusing model definition.

If UserProfile is going to be optional, I'd still lean toward creating and setting immediately in the cases where it's going to exist. Doing so prevents any developer on the project from using get when they need to use get_or_create and thus prevents that entire class of bugs from existing.

The only case where I could imagine not creating and setting it immediately, would be the case where its creation took a significant amount of time. In which case, I might do it asynchronously using Celery, or a similar framework.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.