Django removes an object from a ManyToMany relationship

How would I remove an object from a many-to-many relationship without deleting the object itself?

Example:

I have models of Moods and Interest .

Mood many-many-many models.ManyToManyField(Interest) interests (these are models.ManyToManyField(Interest) ).

I am creating an instance of Moods called my_mood . In my_moods interests my_moods I have my_interest , i.e.

 >>> my_mood.interests.all() [my_interest, ...] 

How can I remove my_interest from my_mood without deleting any model instance? In other words, how to remove a link without affecting related models?

+80
django many-to-many
Jun 13 2018-11-11T00:
source share
3 answers
 my_mood.interests.remove(my_interest) 

Django relationships docs

Note: you may need to get an instance of my_mood and my_interest using the Django QuerySet API before you can execute this code.

+136
Jun 13 '11 at 16:20
source share

If you need to remove all M2M links without touching the underlying objects, it’s easier to work in the other direction:

 interest.mood_set.clear() 

Although this does not directly concern the issue of OP, in this situation it is often useful.

+28
May 05 '17 at 6:50 a.m.
source share

In your case, you can just clear the relationship

 my_mood.interests.clear() 

Then maybe when you create a new relation in your serializer again, you can do something like this

 interests = Interests.objects.get_or_create(name='Something') my_mood_obj.tags.add(tag[0]) my_mood_obj.save() 
+6
Dec 15 '17 at 6:18
source share



All Articles