Why using ForeignKey and not OneToOne to extend the user profile?

178 views
Skip to first unread message

Léon Dignòn

unread,
Aug 18, 2009, 9:57:58 AM8/18/09
to Django users
Hello,

in the authentication documentation is written that the user profile
should be extended with a foreign key.

- http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

"If you'd like to store additional information related to your users,
Django provides a method to specify a site-specific related model --
termed a "user profile" -- for this purpose.

To make use of this feature, define a model with fields for the
additional information you'd like to store […] and also add a
ForeignKey from your model to the User model, specified with
unique=True to ensure only one instance of your model can be created
for each User."



If you look at the model documentation you can find this extract from
the text.

- http://docs.djangoproject.com/en/dev/ref/models/fields/#ref-models-fields

"A one-to-one relationship. Conceptually, this is similar to a
ForeignKey with unique=True, but the 'reverse' side of the relation
will directly return a single object.

This is most useful as the primary key of a model which "extends"
another model in some way […]"



Why should I use a ForeignKey if I want my user profile extended? If
the reverse side will return a single object, I could spare a little
bit of code, if I just write:
>>> "User.objects.get(username='Leon').avatar"
instead of
>>> "u = User.objects.get(username='Leon')"
>>> "UserProfileExtension.objects.get(user=u).avatar"



Comments are welcome!

-ld

Alex Gaynor

unread,
Aug 18, 2009, 2:52:35 PM8/18/09
to django...@googlegroups.com
Personally I always use a 1-1 field, for both the reasons you mention,
and some automatic caching stuff I have only works automatically with
1-1 fields :)

Alex

--
"I disapprove of what you say, but I will defend to the death your
right to say it." -- Voltaire
"The people's good is the highest law." -- Cicero
"Code can always be simpler than you think, but never as simple as you
want" -- Me

Kenneth Gonsalves

unread,
Aug 18, 2009, 7:22:04 PM8/18/09
to django...@googlegroups.com
On Tuesday 18 Aug 2009 7:27:58 pm Léon Dignòn wrote:
> Why should I use a ForeignKey if I want my user profile extended? If
> the reverse side will return a single object, I could spare a little
>
> bit of code, if I just write:
> >>> "User.objects.get(username='Leon').avatar"
>
> instead of
>
> >>> "u = User.objects.get(username='Leon')"
> >>> "UserProfileExtension.objects.get(user=u).avatar"

I think the reason is partially historical - at one stage the one2one field was
going to be abolished and was quirky - so unique foreign key was a workaround.
Possibly that does not hold now.
--
regards
kg
http://lawgon.livejournal.com

Reply all
Reply to author
Forward
0 new messages