Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForeignKey vs OneToOne field django [duplicate]

I need to extend django user with some additional fields . I found 2 different ways there

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    #other fields

OR

class UserProfile(models.Model):
    user = models.ForeignKey(User)
    #other fields

Aren't they same? After syncing them, i saw no difference in mysql database

like image 459
sumit Avatar asked May 17 '12 15:05

sumit


2 Answers

No, why would you think that? A ForeignKey is a one-to-many relationship - ie a user could have many profiles. A OneToOne is, as the name implies, a one-to-one relationship - a user can only have one profile, which sounds more likely.

like image 89
Daniel Roseman Avatar answered Sep 28 '22 20:09

Daniel Roseman


As @Daniel Roseman said, these are 2 different types of rdbms relationships.

You will find that it distinguishes in the situation where you will have(by mistake probably) more than one profiles for a given user. In that situation myuser.get_profile() will raise a MultipleObjectsReturned exception, since essentially it is doing a get() query, under the hood.

like image 23
rantanplan Avatar answered Sep 28 '22 20:09

rantanplan