一尘不染

django OneToOneField和ForeignKey有什么区别?

django

django OneToOneField和ForeignKey有什么区别?


阅读 377

收藏
2020-03-26

共1个答案

一尘不染

请注意,OneToOneField(SomeModel)和之间存在一些差异ForeignKey(SomeModel, unique=True)。如《 Django权威指南》所述:

一对一

一对一的关系。从概念上讲,这与ForeignKeywith 相似unique=True,但是关系的“反向”侧将直接返回单个对象。

OneToOneField“反向”关系相反,ForeignKey“反向”关系返回a QuerySet


例如,如果我们有以下两个模型(下面是完整的模型代码):

  1. Car 模型用途 OneToOneField(Engine)
  2. Car2模型用途 ForeignKey(Engine2, unique=True)

从内部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
2020-03-26