Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

many to many - Django removing object from ManyToMany relationship

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...