I have the following model:
One
name (Char)
Many
one (ForeignKey,blank=True,null=True)
title (Char)
I want to delete a One instance and all related objects should loose their relation to the One instance. At the moment my code looks like this:
one=One.objects.get(<some criterion>)
more=Many.objects.filter(one=one)
for m in more
m.one=None
m.save()
#and finally:
one.delete()
what does the code do? It finds the object, that should be deleted then searches for related objects, sets their ForeignKey to None and finally deletes the One instance. But somewhere in that process it also manages to kill all related objects (Many instances) in the process. My question is: Why are those related objects deleted and how do I prevent this?
The code given is correct. My problem when asking the question was a typo in my implementation.
shame on me
well... there is still a bit that could be improved on:
more=Many.objects.filter(one=one)
for m in more
m.one=None
m.save()
#and finally:
one.delete()
can be written as:
for m in one.many_set.all()
m.one=None
m.save()
one.delete()
which is equivalent to:
one.many_set.clear()
one.delete()