title: Swapping values in a OneToOneField: IntegrityError
body: <p>I have the following object:</p>
  
  <pre><code>from django.db import models
  
  class Page(models.Model):
      prev_sibling = models.OneToOneField('self', related_name='next_sibling',
                                          null=True, blank=True)
  </code></pre>
  
  <p>I have several instances of these objects. Let's say, <code>A, B, C</code> and <code>D</code>. I have assigned the sibling relationships such that <code>A</code> has <code>B</code> as a <code>prev_sibling</code>, and <code>C</code> has <code>D</code> as <code>prev_sibling</code>.</p>
  
  <p>Now imagine I want to swap <code>B</code> and <code>D</code> around. I simply re-assign the attributes, as follows:</p>
  
  <pre><code>A.prev_sibling = D
  A.save()
  C.prev_sibling = B
  C.save()
  </code></pre>
  
  <p>However, this fails with an <code>IntegrityError</code>, as I no longer satisfy the uniqueness constraint that is implied by a <code>OneToOneField</code> after the first <code>save()</code>.</p>
  
  <p>I tried wrapping the code in a transaction, hoping that that would make sure the save would occur atomically, and thus prevent the temporary constraint breach, like so:</p>
  
  <pre><code>from django.db import transaction
  
  with transaction.atomic():
      A.prev_sibling = D
      A.save()
      C.prev_sibling = B
      C.save()
  </code></pre>
  
  <p>But that did not work. What is the right way to resolve this? </p>
  
  <p><strong>EDIT:</strong> For the record: I also tried sequentially assigning and then saving (as follows), but as one might expect, the behaviour is no different.</p>
  
  <pre><code>with transaction.atomic():
      A.prev_sibling = D
      C.prev_sibling = B
      A.save()
      C.save()
  </code></pre>