django OneToOneField和ForeignKey有什么区别?
请注意,OneToOneField(SomeModel)和之间存在一些差异ForeignKey(SomeModel, unique=True)。如《 Django权威指南》所述:
OneToOneField(SomeModel)
ForeignKey(SomeModel, unique=True)
一对一
一对一的关系。从概念上讲,这与ForeignKeywith 相似unique=True,但是关系的“反向”侧将直接返回单个对象。
ForeignKeywith
unique=True
与OneToOneField“反向”关系相反,ForeignKey“反向”关系返回a QuerySet。
OneToOneField
ForeignKey
a QuerySet
例 例如,如果我们有以下两个模型(下面是完整的模型代码):
Car
OneToOneField(Engine)
Car2
ForeignKey(Engine2, unique=True)
从内部python manage.py shell执行以下操作:
python manage.py shell
OneToOneField 例
>>> from testapp.models import Car, Engine >>> c = Car.objects.get(name='Audi') >>> e = Engine.objects.get(name='Diesel') >>> e.car <Car: Audi>
ForeignKey与unique=True例子
>>> from testapp.models import Car2, Engine2 >>> c2 = Car2.objects.get(name='Mazda') >>> e2 = Engine2.objects.get(name='Wankel') >>> e2.car2_set.all() [<Car2: Mazda>]
型号代码
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, on_delete=models.CASCADE) def __unicode__(self): return self.name