aladagemre
aladagemre

Reputation: 602

Django: User vs UserProfile

I'm building a site where we ask users several personal details (birth date, phone number, address, marital status etc. many more).

class User(AbstractUser):
    birth_date = ...
    phone_number = ...

class User(AbstractUser):
    pass


class UserProfile(models.Model):
    user = models.OneToOneField(
        User,
        to_field="id",
        primary_key=True,
        on_delete=models.CASCADE,
        related_name="user_profile",
    )
    birth_date = ...
    phone_number = ...

Which one is the best practice?

Upvotes: 0

Views: 472

Answers (2)

devaerial
devaerial

Reputation: 2201

As always the answer will be "it depends". If your users might have different types of profiles/roles that may require additional set of fields I would go with the second option because it would allow you to have one user model that can combine traits and functionalities of several users. Depending on situation you can call specific method of profile (look for Delegation pattern for more examples).

Upvotes: 1

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7434

This is subjective, based on each ones opinion/needs. But will go over the technical differences:

  • Option 1 is easier to use in your code and more efficient as you don't have to do JOINs between tables in order to get all information

  • Option 2 will make the model look cleaner, with only the most important fields present. This is helpful for data engineers or data analyst who work a lot on SQL visualisation tools

Unless UserProfile has 20+ fields, I would personally go with Option 1.

Upvotes: 2

Related Questions