开发者

How do I delete an object in a django relation (While keeping all related objects)?

开发者 https://www.devze.com 2023-01-09 21:03 出处:网络
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 i

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 manage开发者_运维百科s 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()


You can use update() in first place:

Many.objects.filter(one=one).update(one=None)

I think that Django deletes related object on program level (without on delete cascade in DBMS). So probably your objects are in some kind of cache and Django still thinks that they are related to one object.

Try to list the related objects before you delete.

print one.many_set
one.delete()

If you still have any objects in this set you probably should fetch one from DB again, and then delete. Or you can use delete():

One.objects.filter(<criteria>).delete()
0

精彩评论

暂无评论...
验证码 换一张
取 消