Django model OneToOneField and ForeignKey What is the difference?

ForeignKey is said to be one-to-many, and both a car example:

There are two parts table, a table is the wheel, the other is the engine table. Both tables have a car field, indicating that corresponding to the vehicle accessory.
The wheel, it corresponds to a case where a plurality of normal car, so the car ForeignKey field should be represented.
For engines, one engine might only corresponds to a car, it is necessary to use OneToOneField.

OneToOneField (someModel) can be understood as ForeignKey (SomeModel, unique = True).

Both reverse lookup there is a difference:

ForeignKey reverse lookup returns a list of (a car and a plurality of wheels).

OneToOneField reverse lookup returns a model example (because one relationship).

Additional supplement:

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)

Quoted from REDICE , invasion deleted

Guess you like

Origin www.cnblogs.com/luowenConnor/p/11563573.html