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
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.
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.
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