OneToOneField (one-to-one) realizes, in object orientation, the notion of composition, while ForeignKey (one-to-many) relates to agregation.
Be careful to realize that there are some differences between
Be careful to realize that there are some differences between
OneToOneField(SomeModel)
and ForeignKey(SomeModel, unique=True)
.
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.
(one-to-one field )(one-to-one)== (
ForeignKey
with unique=True)(
one-to-many)ForeignKey
="reverse" relation returns a QuerySet
.
one-to-one field = reverse" side of the relation will directly return a single object.
MODEL
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)
def __unicode__(self):
return self.name
Example
For example, if we have the following two models (full model code below):
Car
model usesOneToOneField(Engine)
Car2
model usesForeignKey(Engine2, unique=True) means Engine2 can have many Car2 instance queryset
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>] #this is queryset
Another Explaination:
The best and the most effective way to learn new things is to see and study real world practical examples. Suppose for a moment that you want to build a blog in django where reporters can write and publish news articles. The owner of the online newspaper wants to allow each of his reporters to publish as many articles as they want, but does not want different reporters to work on the same article. This means that when readers go and read an article they will se only one author in the article.
For example: Article by John, Article by Harry, Article by Rick. You can not have Article by Harry & Rick because the boss does not want two or more authors to work on the same article.
How can we solve this 'problem' with the help of django? The key to the solution of this problem is the django
ForeignKey
.
The following is the full code which can be used to implement the idea of our boss.
from django.db import models
# Create your models here.
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
def __unicode__(self):
return self.first_name
class Article(models.Model):
title = models.CharField(max_length=100)
reporter = models.ForeignKey(Reporter)
def __unicode__(self):
return self.title
Run
python manage.py syncdb
to execute the sql code and build the tables for your app in your database. Then use python manage.py shell
to open a python shell.
Create the Reporter object R1.
In [49]: from thepub.models import Reporter, Article
In [50]: R1 = Reporter(first_name='Rick')
In [51]: R1.save()
Create the Article object A1.
In [5]: A1 = Article.objects.create(title='TDD In Django', reporter=R1)
In [6]: A1.save()
Then use the following piece of code to get the name of the reporter.
In [8]: A1.reporter.first_name
Out[8]: 'Rick'
Now create the Reporter object R2 by running the following python code.
In [9]: R2 = Reporter.objects.create(first_name='Harry')
In [10]: R2.save()
Now try to add R2 to the Article object A1.
In [13]: A1.reporter.add(R2)
It does not work and you will get an AttributeError saying 'Reporter' object has no attribute 'add'.
As you can see an Article object can not be related to more than one Reporter object.
What about R1? Can we attach more than one Article objects to it?
In [14]: A2 = Article.objects.create(title='Python News', reporter=R1)
In [15]: R1.article_set.all()
Out[15]: [<Article: Python News>, <Article: TDD In Django>]
This practical example shows us that django
ForeignKey
is used to define many-to-one relationships.OneToOneField
is used to create one-to-one relationships.
We can use
reporter = models.OneToOneField(Reporter)
in the above models.py file but it is not going to be useful in our example as an author will not be able to post more than one article.
Each time you want to post a new article you will have to create a new Reporter object. This is time consuming, isn't it?
I highly recommend to try the example with the
OneToOneField
and realize the difference. I am pretty sure that after this example you will completly know the difference between django OneToOneField
and django ForeignKey
.
yurtdışı kargo
ReplyDeleteresimli magnet
instagram takipçi satın al
yurtdışı kargo
sms onay
dijital kartvizit
dijital kartvizit
https://nobetci-eczane.org/
SW2CE
Portekiz yurtdışı kargo
ReplyDeleteRomanya yurtdışı kargo
Slovakya yurtdışı kargo
Slovenya yurtdışı kargo
İngiltere yurtdışı kargo
JQV
https://bayanlarsitesi.com/
ReplyDeleteManisa
Denizli
Malatya
Çankırı
75D
Erzurum
ReplyDeleteistanbul
Ağrı
Malatya
Trabzon
6CCJİ
elazığ
ReplyDeletesakarya
zonguldak
adıyaman
antep
02P
ankara parça eşya taşıma
ReplyDeletetakipçi satın al
antalya rent a car
antalya rent a car
ankara parça eşya taşıma
CBLJ
Antep Lojistik
ReplyDeleteYalova Lojistik
Erzincan Lojistik
Tekirdağ Lojistik
Elazığ Lojistik
C21
yalova evden eve nakliyat
ReplyDeletetunceli evden eve nakliyat
giresun evden eve nakliyat
ağrı evden eve nakliyat
van evden eve nakliyat
N5LOA
düzce evden eve nakliyat
ReplyDeletedenizli evden eve nakliyat
kırşehir evden eve nakliyat
çorum evden eve nakliyat
afyon evden eve nakliyat
MLU8NC
BB05A
ReplyDeleteManisa Evden Eve Nakliyat
İzmir Lojistik
Kütahya Lojistik
Urfa Evden Eve Nakliyat
Iğdır Parça Eşya Taşıma
C6BF0
ReplyDeleteGiresun Parça Eşya Taşıma
Elazığ Lojistik
Osmo Coin Hangi Borsada
Yenimahalle Boya Ustası
Binance Referans Kodu
Kilis Şehir İçi Nakliyat
Karaman Parça Eşya Taşıma
Osmaniye Lojistik
Muş Parça Eşya Taşıma
B5A84
ReplyDeleteIsparta Evden Eve Nakliyat
Trabzon Şehirler Arası Nakliyat
Ordu Şehir İçi Nakliyat
Balıkesir Şehir İçi Nakliyat
Çerkezköy Kurtarıcı
Osmaniye Şehir İçi Nakliyat
Kars Evden Eve Nakliyat
Gümüşhane Parça Eşya Taşıma
Kırıkkale Lojistik
A83FD
ReplyDeleteÜnye Fayans Ustası
Çerkezköy Buzdolabı Tamircisi
Batıkent Parke Ustası
Referans Kimliği Nedir
Erzincan Evden Eve Nakliyat
Kütahya Evden Eve Nakliyat
Referans Kimliği Nedir
Çerkezköy Mutfak Dolabı
Ünye Evden Eve Nakliyat
2EA1C
ReplyDeleteMexc Güvenilir mi
Mamak Fayans Ustası
Mersin Evden Eve Nakliyat
Kayseri Evden Eve Nakliyat
Ankara Parke Ustası
Karabük Evden Eve Nakliyat
Amasya Evden Eve Nakliyat
Ankara Boya Ustası
Adana Evden Eve Nakliyat
AF733
ReplyDeleteÜnye Asma Tavan
Kalıcı Makyaj
Coin Nedir
Vindax Güvenilir mi
Ağrı Evden Eve Nakliyat
Bitci Güvenilir mi
Sakarya Evden Eve Nakliyat
Isparta Evden Eve Nakliyat
Ünye Boya Ustası
7162B
ReplyDeleteMamak Parke Ustası
Sincan Parke Ustası
Çerkezköy Fayans Ustası
Binance Referans Kodu
Ünye Çatı Ustası
Çerkezköy Marangoz
Gümüşhane Evden Eve Nakliyat
Eryaman Alkollü Mekanlar
Binance Referans Kodu
C00D2
ReplyDeleteNevşehir Evden Eve Nakliyat
Bingöl Evden Eve Nakliyat
Erzincan Evden Eve Nakliyat
Binance Referans Kodu
Ünye Koltuk Kaplama
Malatya Evden Eve Nakliyat
Çerkezköy Boya Ustası
Poloniex Güvenilir mi
Referans Kimliği Nedir
76B5D
ReplyDeletetrabzon canli sohbet bedava
bayburt sesli sohbet siteler
adana sesli sohbet
aksaray mobil sohbet et
erzincan görüntülü sohbet ücretsiz
mobil sohbet odaları
gümüşhane görüntülü sohbet canlı
elazığ bedava sohbet odaları
aydın telefonda rastgele sohbet
BC5DA
ReplyDeletemaraş görüntülü sohbet
eskişehir sohbet odaları
isparta görüntülü sohbet
telefonda sohbet
muğla telefonda rastgele sohbet
kadınlarla sohbet et
çanakkale canlı görüntülü sohbet odaları
yalova canli sohbet bedava
bursa mobil sohbet odaları
6B2B2
ReplyDeletetrabzon ücretsiz sohbet sitesi
karaman yabancı sohbet
gümüşhane kızlarla canlı sohbet
çanakkale sohbet odaları
manisa görüntülü sohbet kızlarla
rastgele sohbet uygulaması
amasya sohbet
sohbet muhabbet
giresun canlı sohbet odası
F672D
ReplyDeletekadınlarla görüntülü sohbet
ığdır Yabancı Canlı Sohbet
mobil sohbet chat
niğde ücretsiz sohbet
kars mobil sohbet sitesi
kadınlarla sohbet
rastgele sohbet odaları
Balıkesir Mobil Sohbet Odaları
mobil sesli sohbet
4856B
ReplyDeleteAntep Mobil Sesli Sohbet
telefonda kızlarla sohbet
görüntülü canlı sohbet
muğla sesli sohbet mobil
ardahan görüntülü sohbet uygulama
Bingöl Görüntülü Sohbet Uygulama
niğde görüntülü sohbet yabancı
sakarya kadınlarla sohbet et
sinop kadınlarla görüntülü sohbet
8A0FD
ReplyDeleteTumblr Takipçi Satın Al
Flare Coin Hangi Borsada
Instagram Takipçi Hilesi
Luffy Coin Hangi Borsada
Binance Hangi Ülkenin
Periscope Takipçi Satın Al
Bitranium Coin Hangi Borsada
Kwai Takipçi Satın Al
Periscope Beğeni Satın Al
AB64C
ReplyDeleteBitranium Coin Hangi Borsada
Onlyfans Takipçi Hilesi
Baby Doge Coin Hangi Borsada
Expanse Coin Hangi Borsada
Kwai Takipçi Hilesi
Bitcoin Nasıl Oynanır
Görüntülü Sohbet
Kaspa Coin Hangi Borsada
Facebook Sayfa Beğeni Hilesi
A8CD1
ReplyDeletekripto para haram mı
en az komisyon alan kripto borsası
paribu
telegram kripto
bitcoin hangi bankalarda var
binance referans kimliği
cointiger
canlı sohbet ucretsiz
gate io
83068
ReplyDeletebitcoin nasıl kazanılır
filtre kağıdı
telegram kripto grupları
June 2024 Calendar
August 2024 Calendar
gate io
referans kodu
kripto ne demek
binance
0816D
ReplyDeleteElbeyli
Çiftlik
Onikişubat
Alanya
Felahiye
Dereli
Başyayla
Türk İfşa
Talas