views:

190

answers:

2

I need to avoid cascading deletes on a foreign key, but it's a OneToOneField(), like:

class MyModel(models.Model):
    def delete(self):
        self.mysubmodel.clear()  # Breaks because self.cartitem is not a QuerySet.
        super(MyModel, self).delete()

class MySubModel(models.Model):
    mymodel = models.OneToOneField(MyModel)

This version would work (but I can't use this version):

class MyModel(models.Model):
    def delete(self):
        self.mysubmodel_set.clear()  # Works because self.mysubmodel_set is a QuerySet.
        super(MyModel, self).delete()

class MySubModel(models.Model):
    mymodel = models.ForeignKey(MyModel)
A: 

What is expected behavior here? I mean, o2o does not allow null values?

Dmitry Shevchenko
You can't use null=True in a OneToOneField()?
orokusaki
The behavior is that I'm creating a sub item that will be based off an item, but the subitem has a dependent and therefore can't be deleted unless it's dependent is deleted, so I can't just have subitems being deleted because a item goes.
orokusaki
+2  A: 

Setting the field to None in the delete method should work:

self.mysubmodel = None
Daniel Roseman
And that won't cause any problems down the road?
orokusaki