Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Be careful to realize that there are some differences between <code>OneToOneField(SomeModel)</code> and <code>ForeignKey(SomeModel, unique=True)</code>. As stated in <a href="http://djangobook.com/model-definition-reference/#leanpub-auto-onetoonefield" rel="noreferrer"><em>The Definitive Guide to Django</em></a>:</p> <blockquote> <p><strong>OneToOneField</strong></p> <p>A one-to-one relationship. Conceptually, this is similar to a <code>ForeignKey</code> with <code>unique=True</code>, but the "reverse" side of the relation will directly return a single object.</p> </blockquote> <p>In contrast to the <code>OneToOneField</code> "reverse" relation, a <code>ForeignKey</code> "reverse" relation returns a <code>QuerySet</code>.</p> <h2>Example</h2> <p>For example, if we have the following two models (full model code below):</p> <ol> <li><code>Car</code> model uses <code>OneToOneField(Engine)</code></li> <li><code>Car2</code> model uses <code>ForeignKey(Engine2, unique=True)</code></li> </ol> <p>From within <code>python manage.py shell</code> execute the following:</p> <h3><code>OneToOneField</code> Example</h3> <pre><code>&gt;&gt;&gt; from testapp.models import Car, Engine &gt;&gt;&gt; c = Car.objects.get(name='Audi') &gt;&gt;&gt; e = Engine.objects.get(name='Diesel') &gt;&gt;&gt; e.car &lt;Car: Audi&gt; </code></pre> <h3><code>ForeignKey</code> with <code>unique=True</code> Example</h3> <pre><code>&gt;&gt;&gt; from testapp.models import Car2, Engine2 &gt;&gt;&gt; c2 = Car2.objects.get(name='Mazda') &gt;&gt;&gt; e2 = Engine2.objects.get(name='Wankel') &gt;&gt;&gt; e2.car2_set.all() [&lt;Car2: Mazda&gt;] </code></pre> <h2>Model Code</h2> <pre><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, on_delete=models.CASCADE) def __unicode__(self): return self.name </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload