ForeignKey vs OneToOne字段django [英] ForeignKey vs OneToOne field django
本文介绍了ForeignKey vs OneToOne字段django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要扩展django用户一些附加字段。我发现有两种不同的方式:
class UserProfile(models.Model):
user = models.OneToOneField(User)
#其他字段
或
class UserProfile(models.Model):
/ pre>
user = models.ForeignKey(User)
#other fields
不一样?在同步它们之后,我看到mysql数据库没有区别。
解决方案不,你为什么会这么认为?外键是一对多的关系 - 即用户可以拥有许多个人资料。顾名思义,OneToOne就是一对一的关系 - 用户只能拥有一个配置文件,这种配置更有可能。
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.
这篇关于ForeignKey vs OneToOne字段django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文