Django removing object from ManyToMany relationship

DjangoMany to-Many

Django Problem Overview


How would I delete an object from a Many-to-Many relationship without removing the actual object?

Example:

I have the models Moods and Interest.

Mood has a many-to-many field interests (which is a models.ManyToManyField(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, ...]

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?

Django Solutions


Solution 1 - Django

my_mood.interests.remove(my_interest)

Django's Relations Docs

Note: you might have to get an instance of my_mood and my_interest using Django's QuerySet API before you can execute this code.

Solution 2 - Django

If you need to remove all M2M references without touching the underlying objects, it's easier to work from the other direction:

interest.mood_set.clear()

While this does not directly address the OP's question, it's often useful in this situation.

Solution 3 - Django

In your case you can simply clear the relationship

my_mood.interests.clear()

Then perhaps when you are again creating new relation in your serializer 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()

Solution 4 - Django

model.field.remove(object_you_want_to_remove)
In this case use: my_mood.interests.remove(my_interest)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNachshon SchwartzView Question on Stackoverflow
Solution 1 - DjangoDrTyrsaView Answer on Stackoverflow
Solution 2 - DjangoshackerView Answer on Stackoverflow
Solution 3 - DjangoSabyasachi View Answer on Stackoverflow
Solution 4 - DjangoHimaloy MondalView Answer on Stackoverflow