gpt4 book ai didi

django - django OneToOneField 和 ForeignKey 有什么区别?

转载 作者:行者123 更新时间:2023-11-28 19:32:04 25 4
gpt4 key购买 nike

Django OneToOneFieldForeignKey 有什么区别?

最佳答案

OneToOneField(SomeModel)ForeignKey(SomeModel, unique=True) 之间的区别,如 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.

OneToOneField“反向”关系相反,ForeignKey“反向”关系返回一个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>

ForeignKeyunique=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

关于django - django OneToOneField 和 ForeignKey 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5870537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com