OneToOneFieldDjango和有什么区别ForeignKey?
OneToOneField
ForeignKey
The Definitive Guide to DjangoOneToOneField(SomeModel)之间ForeignKey(SomeModel, unique=True)的区别: __
OneToOneField(SomeModel)
ForeignKey(SomeModel, unique=True)
一对一字段 一对一的关系。从概念上讲,这类似于ForeignKeywith unique=True,但关系的“反向”侧将直接返回单个对象。
一对一字段
一对一的关系。从概念上讲,这类似于ForeignKeywith unique=True,但关系的“反向”侧将直接返回单个对象。
unique=True
与OneToOneField“反向”关系相反,ForeignKey“反向”关系返回 a QuerySet。
QuerySet
例如,如果我们有以下两个模型(完整模型代码如下):
Car
OneToOneField(Engine)
Car2
ForeignKey(Engine2, unique=True)
从内部python manage.py shell执行以下操作:
python manage.py shell
>>> 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