0

有个问题。假设我有两个处于多对多关系的模型(文章、出版物)。文章 A 在出版物一、二和三中。我想从这些出版物中删除它并将其放入出版物 X。django 文档涵盖了删除对象和添加对象,但我不想删除或添加对象,只是“移动”它们。我该怎么做?

提前致谢,

Ĵ

4

2 回答 2

2
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()
于 2009-04-21T19:14:20.480 回答
1

您只需删除与出版物 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)

在django 文档中有一个很好的例子来说明如何做到这一点。

于 2009-04-21T19:12:04.543 回答