Home > Net >  Django: User vs UserProfile
Django: User vs UserProfile

Time:10-08

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

  • Option 1: User model only. Put these personal fields in class User(AbstractUser) model
class User(AbstractUser):
    birth_date = ...
    phone_number = ...

  • Option 2: User UserProfile models: separate login-related data (User) from personal data (UserProfile) like:
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?

CodePudding user response:

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.

CodePudding user response:

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).

  • Related