Django从ManyToMany关系中删除对象 [英] Django removing object from ManyToMany relationship
问题描述
如果不删除实际对象,我将如何从多对多关系中删除对象?
How would i delete an object from a Many-to-Many relationship without removing the actual object?
示例:
我有模型心情
和兴趣
。
心情有许多到很多字段兴趣
(这是一个 models.ManyToManyField(兴趣)
)。
'Mood' has a many to many field interests
(which is a models.ManyToManyField(Interest)
).
我创建一个 Moods
的实例称为 my_mood
。在my_moods的兴趣领域,我有 my_interest
,意思是
I create an instance of Moods
called my_mood
. In my_moods's interests field I have my_interest
, meaning
>>> my_mood.interests.all()
[my_interest, ...]
从my_mood中删除my_interest,而不删除任何一个模型实例?换句话说,如何在不影响相关模型的情况下删除关系?
How do I remove my_interest from my_mood without deleting either model instance? In other words, how do I remove the relationship without affecting the related models?
推荐答案
my_mood.interests.remove(my_interest)
注意:您可能需要使用my_mood和my_instance的实例 Django的QuerySet API ,然后才能执行此代码。
Note: you might have to get an instance of my_mood and my_instance using Django's QuerySet API before you can execute this code.
这篇关于Django从ManyToMany关系中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!