views:

252

answers:

2

Hey all,

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

+1  A: 

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.

vezult
+2  A: 
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()
Andrea Di Persio