zoukankan      html  css  js  c++  java
  • 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,侵删

  • 相关阅读:
    tar命令详解(很好的中文说明) zhumao
    Grep学习笔记(转载) zhumao
    Linux命令集(转载) zhumao
    GNU/Linux问题集 (好文章,好手册) zhumao
    Sed学习笔记(转载) zhumao
    加密和显示图片的PHP代码(可以使用) zhumao
    用wget使用认证用户从ftp站点下载文件 zhumao
    Sendmail学习笔记 ... (转载) zhumao
    一段垃圾代码,自己写的(发送图书馆新书通告) zhumao
    CLR自定义.NET控件制作(2)——添加自定义属性、方法和事件
  • 原文地址:https://www.cnblogs.com/luowenConnor/p/11563573.html
Copyright © 2011-2022 走看看