Accessing the automatic reverse relationship on an instance (w.sprocket in the following example) causes some type of caching to happen which results in my Sprocket getting caught up in a cascade delete() of a Widget erroneously. The following example works without the print statement, and my Sprocket s exists at the end. If I 'print w.sprocket' before clearing the relationship, my Sprocket gets deleted along with my Widget when it shouldn't.
class Widget(models.Model):
name = models.CharField(max_length=10)
def __unicode__(self):
return u'%s(%s)'%(self.name,self.pk)
class Sprocket(models.Model):
name = models.CharField(max_length=10)
w = models.OneToOneField(Widget, null=True, blank=True)
def __unicode__(self):
return u'%s(%s)'%(self.name,self.pk)
And the following sequence of operations:
w=Widget(name="Some Widget")
w.save()
s=Sprocket(name="Some Sprocket")
s.w=w
s.save()
assert Widget.objects.all().count()==1
assert Sprocket.objects.all().count()==1
#print w.sprocket
s.w=None
s.save()
w.delete()
assert Widget.objects.all().count()==0
assert Sprocket.objects.all().count()==1