Django模型中的OneToOneField和ForeignKey有什么区别?

来源:互联网 发布:http mac地址 编辑:程序博客网 时间:2024/04/29 18:31


转自:Django模型中的OneToOneField和ForeignKey有什么区别?


在stackoverflow发了个帖子问这个问题(http://stackoverflow.com/questions/5870537/whats-the-difference-between-django-onetoonefield-and-foreignkey),马上就有人回复了:


说是ForeignKey是one-to-many的,并举了一个车的例子:

有两个配件表,一个是车轮表,另一个是引擎表。两个表都有一个car字段,表示该配件对应的车。
对于车轮来说,多个对应一个car的情况很正常,所以car字段应该用ForeignKey来表示。
对于引擎来说,一个引擎只可能对应一个car,所以必须用OneToOneField。


OneToOneField(someModel) 可以理解为 ForeignKey(SomeModel, unique=True)。

 

两者的反向查询是有差别的:

ForeignKey反向查询返回的是一个列表(一个车有多个轮子)。

OneToOneField反向查询返回的是一个模型示例(因为一对一关系)。

 

另外的补充说明:

Be careful to realize that there are some differences between OneToOneField(SomeModel) andForeignKey(SomeModel, unique=True). As stated in The Definitive Guide to Django:

OneToOneField

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.

In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns aQuerySet.

Example

For example, if we have the following two models (full model code below):

  1. Car model uses OneToOneField(Engine)
  2. Car2 model uses ForeignKey(Engine2, unique=True)

From within python manage.py shell execute the following:

OneToOneField Example

>>> from testapp.models import Car, Engine>>> c = Car.objects.get(name='Audi')>>> e = Engine.objects.get(name='Diesel')>>> e.car<Car: Audi>

ForeignKey with unique=True Example

>>> from testapp.models import Car2, Engine2>>> c2 = Car2.objects.get(name='Mazda')>>> e2 = Engine2.objects.get(name='Wankel')>>> e2.car2_set.all()[<Car2: Mazda>]

Model Code

from django.db import modelsclass Engine(models.Model):    name = models.CharField(max_length=25)    def __unicode__(self):        return self.nameclass Car(models.Model):    name = models.CharField(max_length=25)    engine = models.OneToOneField(Engine)    def __unicode__(self):        return self.nameclass Engine2(models.Model):    name = models.CharField(max_length=25)    def __unicode__(self):        return self.nameclass Car2(models.Model):    name = models.CharField(max_length=25)    engine = models.ForeignKey(Engine2, unique=True)    def __unicode__(self):        return self.name

 

 

1 0
原创粉丝点击