ForeignKey vs OneToOne field django [duplicate]

2020-07-11 08:00发布

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

2条回答
欢心
2楼-- · 2020-07-11 09:02

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.

查看更多
萌系小妹纸
3楼-- · 2020-07-11 09:06

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.

查看更多
登录 后发表回答