Reputation: 768
General question here (more specifically for Django/Python), when creating a model such as a Company
for example, and several users (employees) are going to be related to such model, how should the different models be related?
I.e. a user profile will be related to a user object via a OneToOneField. But should the Company object be related by a ForeignKey to the User object or the UserProfile object, and why is this the appropriate way?
So
class UserProfile(models.Model): # For the Company Employees
user = models.OneToOneField(UserModel, related_name='employeeprofilemodel', on_delete=models.CASCADE, blank=True,
null=True)
...
company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True)
or
class User(AbstractBaseUser): # For all Users
...
company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True)
Upvotes: 1
Views: 644
Reputation: 9235
This is more of an opinion based question, rather than technicality. I'd recommend the former way, which is creating a One-to-one relationship with the AUTH_USER_MODEL
. Then, you could store the employee related data in the User Profile table which can be related to the Company table through a ForeignKey relationship. The advantage of this kind of database schema is that, you can alter the User table(which is AUTH_USER_MODEL
) in future (if needed, of course) without affecting the employee details which maybe sensitive in nature. The User table lives independent of the Company table in the database and could be used for the Authorisation. Also less data is carried during db queries and implicitly a small level of optimisation can be achieved. I assume this is more appropriate way than extending from the auth.User
model.
The latter way could compromise the above said sensitive data whenever a database refactoring ever required. Also, the queries would be much more heavy, when the User models have more data than necessary regarding the users. Extra care for optimisation may be required when handling the db queries with user tables.
Upvotes: 3