Reputation: 190
Got a question. Say I have two models in a many-to-many relationship (Article, Publication). Article A is in Publication One, Two, and Three. I want to remove it from those publications and put it into Publication X. The django documentation covers deleting objects and adding objects, but I don't want to delete nor add objects, merely 'move' them. How would I do this?
Thanks in advance,
J
Upvotes: 0
Views: 824
Reputation: 3266
pubx = Pubblication(.....)
pubx.save()
article_obj = Article.objects.get(id=1)
remove_from_lst = ["pubblication a", "pubblication b", "pubblication c"]
remove_from_qs = Pubblication.objects.filter(name__in=remove_from_lst)
for qs in remove_from_qs:
article_obj.pubblications.remove(qs)
article_obj.pubblications.add(pubx)
article.save()
Upvotes: 2
Reputation: 5243
You just need to remove the associations with publications 1, 2, and 3, and create an association with publication x:
# `a` being an instance of the Article object, pub{1,2,3,x}, being
# instances of Publication objects
a.publications.remove(pub1)
a.publications.remove(pub2)
a.publications.remove(pub3)
a.publications.add(pubx)
There is a good example of how to do this in the django docs.
Upvotes: 1