说是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):
Car model uses OneToOneField(Engine)
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 models
class Engine(models.Model):
name = models.CharField(max_length=25)
def __unicode__(self):
return self.name
class Car(models.Model):
name = models.CharField(max_length=25)
engine = models.OneToOneField(Engine)
def __unicode__(self):
return self.name
class Engine2(models.Model):
name = models.CharField(max_length=25)
def __unicode__(self):
return self.name
class Car2(models.Model):
name = models.CharField(max_length=25)
engine = models.ForeignKey(Engine2, unique=True)
引自redice,侵删
原文地址:https://www.cnblogs.com/luowenConnor/p/11563573.html