I'm finding conflicting information on whether to use OneToOneField(User)
or ForeignKey(User, unique=True)
when creating a UserProfile
model by extending the Django User model.
Is it better to use this?:
class UserProfile(models.Model): user = models.ForeignKey(User, unique=True)
or this?:
class UserProfile(models.Model): user = models.OneToOneField(User)
The Django Doc specifies OneToOneField
, while the Django Book example uses ForeignKey
.
James Bennett also has two Blog posts that providing conflicting examples as well:
In the former post, Bennett provides some reasons why he switched to using ForeignKey
instead of OneToOneField
, but I don't quite get it, especially when I see other posts that recommend the opposite.
I'm curious to know your preference and why. Or, does it even matter?
The only real reason given in the article is that it can be set up so that the admin page for User
will show both the fields in User
and UserProfile
. This can be replicated with a OneToOneField
with a little elbow grease, so unless you're addicted to showing it in the admin page with no work at the cost of a bit of clarity ("We can create multiple profiles per user?! Oh no, wait, it's set unique.") I'd use OneToOneField
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With