问题描述
Django中的 models.ForeignKey(Modelname,unique = True)
和 models.OneToOneField
之间有什么区别? 我应该在哪里使用 models.OneToOneField
和 models.ForeignKey(Modelname,unique =真的)
?
A OneToOneField
非常类似于 ForeignKey
与 unique = True
。除非您正在执行多个表继承,否则您必须使用 OneToOneField
,唯一真正的区别是访问相关对象的api。
在中说:
让我们用一个例子来说明这是什么意思。考虑两个模型, Person
和地址
。我们假设每个人都有一个唯一的地址。
class Person(models.Model):
name = models .CharField(max_length = 50)
address = models.ForeignKey('Address',unique = True)
class地址(models.Model):
street = models.CharField (max_length = 50)
如果您从一个人开始,您可以轻松访问该地址: p>
address = person.address
但是,如果您从地址开始,您必须通过 person_set
管理员来获取该人。
person = address.person_set.get()#可能会提高Person.DoesNotExist
现在我们用 OneToOneField
替换 ForeignKey
。
class Person(models.Model):
name = models.CharField(max_length = 50)
address = models.OneToOneField('地址')
类地址(模型s.Model):
street = models.CharField(max_length = 50)
如果你从一个人开始,您可以以相同的方式访问地址:
address = person.address
现在,我们可以更轻松地从地址访问该人。
person = address.person#可以提高Person.DoesNotExist
What is different between models.ForeignKey(Modelname, unique=True)
and models.OneToOneField
in Django?
Where should I use models.OneToOneField
and models.ForeignKey(Modelname, unique=True)
?
A OneToOneField
is very similar to a ForeignKey
with unique=True
. Unless you are doing multiple table inheritance, in which case you have to use OneToOneField
, the only real difference is the api for accessing related objects.
In the Django docs it says:
Let's show what that means with an example. Consider two models, Person
and Address
. We'll assume each person has a unique address.
class Person(models.Model):
name = models.CharField(max_length=50)
address = models.ForeignKey('Address', unique=True)
class Address(models.Model):
street = models.CharField(max_length=50)
If you start with a person, you can access the address easily:
address = person.address
However if you start with an address, you have to go via the person_set
manager to get the person.
person = address.person_set.get() # may raise Person.DoesNotExist
Now let's replace the ForeignKey
with a OneToOneField
.
class Person(models.Model):
name = models.CharField(max_length=50)
address = models.OneToOneField('Address')
class Address(models.Model):
street = models.CharField(max_length=50)
If you start with a person, you can access the address in the same way:
address = person.address
And now, we can access the person from the address more easily.
person = address.person # may raise Person.DoesNotExist
这篇关于ForeignKey(User,unique = True)和OneToOneField之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!