• Django模型中的OneToOneField和ForeignKey有什么区别?


    说是ForeignKey是one-to-many的,并举了一个车的例子:

    有两个配件表,一个是车轮表,另一个是引擎表。两个表都有一个car字段,表示该配件对应的车。
    对于车轮来说,多个对应一个car的情况很正常,所以car字段应该用ForeignKey来表示。
    对于引擎来说,一个引擎只可能对应一个car,所以必须用OneToOneField。

    OneToOneField(someModel) 可以理解为 ForeignKey(SomeModel, unique=True)。

    两者的反向查询是有差别的:

    ForeignKey反向查询返回的是一个列表(一个车有多个轮子)。

    OneToOneField反向查询返回的是一个模型示例(因为一对一关系)。

    另外的补充说明:

    Be careful to realize that there are some differences between OneToOneField(SomeModel) andForeignKey(SomeModel, unique=True). As stated in 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.

    In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns aQuerySet.

    Example
    For example, if we have the following two models (full model code below):

    Car model uses OneToOneField(Engine)
    Car2 model uses ForeignKey(Engine2, unique=True)
    From within python manage.py shell execute the following:

    OneToOneField Example
    >>> from testapp.models import Car, Engine
    >>> c = Car.objects.get(name='Audi')
    >>> e = Engine.objects.get(name='Diesel')
    >>> e.car
    <Car: Audi>
    
    ForeignKey with unique=True Example
    >>> from testapp.models import Car2, Engine2
    >>> c2 = Car2.objects.get(name='Mazda')
    >>> e2 = Engine2.objects.get(name='Wankel')
    >>> e2.car2_set.all()
    [<Car2: Mazda>]
    

    Model Code

    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)
    

    引自redice,侵删

  • 相关阅读:
    关于程序与语言
    最新笔记请查看
    MySQL 性能优化
    k8s flannel无法跨主机ping通pod的解决方案
    k8s 使用kubeadm部署k8s集群初体验
    MySQL 锁和可重复读的隔离级别结合起来的一个示例(来自MySQL45讲第8章)
    MySQL 可重复读 vs 读提交
    Jenkins配置Linux节点,通过ssh方式在Linux节点自动拉取github代码并执行
    AppScan 使用
    Linux 动态链接库和静态库示例
  • 原文地址:https://www.cnblogs.com/luowenConnor/p/11563573.html
Copyright © 2020-2023  润新知