問(wèn)題描述
我有 Books
、Chapters
和 Pages
的模型.它們都是由 User
編寫(xiě)的:
I've models for Books
, Chapters
and Pages
. They are all written by a User
:
我想做的是復(fù)制現(xiàn)有的 Book
并將它的 User
更新給其他人.皺紋是我還想將所有相關(guān)的模型實(shí)例復(fù)制到 Book
- 所有的 Chapters
和 Pages
也是如此!
What I'd like to do is duplicate an existing Book
and update it's User
to someone else. The wrinkle is I would also like to duplicate all related model instances to the Book
- all it's Chapters
and Pages
as well!
當(dāng)查看 Page
時(shí),事情變得非常棘手 - 新的 Pages
不僅需要更新其 author
字段,而且它們會(huì)還需要指向新的Chapter
對(duì)象!
Things get really tricky when look at a Page
- not only will the new Pages
need to have their author
field updated but they will also need to point to the new Chapter
objects!
Django 支持開(kāi)箱即用的方式嗎?復(fù)制模型的通用算法是什么樣的?
Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like?
干杯,
約翰
更新:
上面給出的類只是說(shuō)明我遇到的問(wèn)題的一個(gè)例子!
The classes given above are just an example to illustrate the problem I'm having!
推薦答案
這不再適用于 Django 1.3,因?yàn)?CollectedObjects 已被刪除.請(qǐng)參閱 變更集 14507
This no longer works in Django 1.3 as CollectedObjects was removed. See changeset 14507
我在 Django Snippets 上發(fā)布了我的解決方案. 它主要基于 django.db.models.query.CollectedObject
用于刪除對(duì)象的代碼:
I posted my solution on Django Snippets. It's based heavily on the django.db.models.query.CollectedObject
code used for deleting objects:
對(duì)于 django >= 2 應(yīng)該有一些微小的變化.所以輸出會(huì)是這樣的:
For django >= 2 there should be some minimal changes. so the output will be like this:
這篇關(guān)于在 Django 中復(fù)制模型實(shí)例及其相關(guān)對(duì)象/用于遞歸復(fù)制對(duì)象的算法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!