What's the difference between Django OneToOneField
and ForeignKey
?
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.
A foreign key relationship is generally known as a many-to-one relationship. Note that the reverse of this relationship is one-to-many (which Django provides tools to access). As the name implies, many objects may be related to one.
One-to-one fields:This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle.
The many-to-one relationship is known as foreign key relationship in Django, here 0 to many objects in one model may be related to one object in another model. A project can have more than one student working on it.
A ForeignKey
is a many-to-one relationship. So, a Car
object might have many instances of Wheel
. Each Wheel
would consequently have a ForeignKey
to the Car
it belongs to. A OneToOneField
would be like an instance of Engine
, where a Car
object can have one and only one.
Differences between OneToOneField(SomeModel)
and ForeignKey(SomeModel, unique=True)
as stated in The Definitive Guide to Django:
OneToOneField
A one-to-one relationship. Conceptually, this is similar to a
ForeignKey
withunique=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 a QuerySet
.
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>]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With