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?
有个问题。假设我在多对多关系中有两个模型(文章,出版物)。 A条在出版物一,二,三。我想将它从那些出版物中删除并将其放入出版物X.django文档包括删除对象和添加对象,但我不想删除或添加对象,只是“移动”它们。我该怎么办?
Thanks in advance,
提前致谢,
J
2 个解决方案
#1
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()
#2
You just need to remove the associations with publications 1, 2, and 3, and create an association with publication x:
您只需要删除与出版物1,2和3的关联,并创建与出版物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.
有一个很好的例子,说明如何在django文档中执行此操作。
#1
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()
#2
You just need to remove the associations with publications 1, 2, and 3, and create an association with publication x:
您只需要删除与出版物1,2和3的关联,并创建与出版物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.
有一个很好的例子,说明如何在django文档中执行此操作。