Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: When extending User, better to use OneToOneField(User) or ForeignKey(User, unique=True)?

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:

  • Extending the User Model
  • User Registration

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?

like image 876
Tony Guinta Avatar asked Jul 11 '10 03:07

Tony Guinta


1 Answers

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.

like image 59
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 21:09

Ignacio Vazquez-Abrams