小编典典

django OneToOneField 和 ForeignKey 有什么区别?

all

OneToOneFieldDjango和有什么区别ForeignKey


阅读 131

收藏
2022-03-11

共1个答案

小编典典

The Definitive Guide to
Django
OneToOneField(SomeModel)之间ForeignKey(SomeModel, unique=True)的区别:
__

一对一字段

一对一的关系。从概念上讲,这类似于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
2022-03-11