我有模特Books
,Chapters
和Pages
.它们都是由User
:
from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter)
我想做的是复制现有的Book
并将其更新User
给其他人.皱纹是我也想复制所有相关模型实例的Book
-它所有的Chapters
和Pages
以及!
当看到a时,事情变得非常棘手Page
- 不仅新的Pages
需要author
更新他们的领域,而且他们还需要指向新的Chapter
对象!
Django是否支持开箱即用的方式?复制模型的通用算法会是什么样的?
干杯,
约翰
更新:
上面给出的类只是一个例子来说明我遇到的问题!
这已不再适用于Django 1.3,因为CollectedObjects已被删除.请参阅changeset 14507
我在Django Snippets上发布了我的解决方案.它主要基于django.db.models.query.CollectedObject
用于删除对象的代码:
from django.db.models.query import CollectedObjects from django.db.models.fields.related import ForeignKey def duplicate(obj, value, field): """ Duplicate all related objects of `obj` setting `field` to `value`. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of `obj`. """ collected_objs = CollectedObjects() obj._collect_sub_objects(collected_objs) related_models = collected_objs.keys() root_obj = None # Traverse the related models in reverse deletion order. for model in reversed(related_models): # Find all FKs on `model` that point to a `related_model`. fks = [] for f in model._meta.fields: if isinstance(f, ForeignKey) and f.rel.to in related_models: fks.append(f) # Replace each `sub_obj` with a duplicate. sub_obj = collected_objs[model] for pk_val, obj in sub_obj.iteritems(): for fk in fks: fk_value = getattr(obj, "%s_id" % fk.name) # If this FK has been duplicated then point to the duplicate. if fk_value in collected_objs[fk.rel.to]: dupe_obj = collected_objs[fk.rel.to][fk_value] setattr(obj, fk.name, dupe_obj) # Duplicate the object and save it. obj.id = None setattr(obj, field, value) obj.save() if root_obj is None: root_obj = obj return root_obj
这是一种复制对象的简便方法.
基本上:
(1)将原始对象的id设置为None:
book_to_copy.id =无
(2)更改'author'属性并保存ojbect:
book_to_copy.author = new_author
book_to_copy.save()
(3)执行INSERT而不是UPDATE
(它没有涉及在页面中更改作者 - 我同意有关重构模型的评论)
我没有在django中尝试过,但是python的深度复制可能对你有用
编辑:
如果实现函数,则可以为模型定义自定义复制行为:
__copy__() and __deepcopy__()
这是http://www.djangosnippets.org/snippets/1282/的编辑
它现在与收集器兼容,后者取代了1.3中的CollectedObjects.
我没有真正测试过这么多,但是用一个约有20,000个子对象的对象测试它,但只有大约三层外键深度.当然使用风险由您自己承担.
对于阅读这篇文章的雄心勃勃的人,您应该考虑将Collector子类化(或者将整个类复制以删除对django API的这个未发布部分的这种依赖性)到类似"DuplicateCollector"的类并编写一个有效的.duplicate方法类似于.delete方法.这将以一种真实的方式解决这个问题.
from django.db.models.deletion import Collector from django.db.models.fields.related import ForeignKey def duplicate(obj, value=None, field=None, duplicate_order=None): """ Duplicate all related objects of obj setting field to value. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of obj. duplicate_order is a list of models which specify how the duplicate objects are saved. For complex objects this can matter. Check to save if objects are being saved correctly and if not just pass in related objects in the order that they should be saved. """ collector = Collector({}) collector.collect([obj]) collector.sort() related_models = collector.data.keys() data_snapshot = {} for key in collector.data.keys(): data_snapshot.update({ key: dict(zip([item.pk for item in collector.data[key]], [item for item in collector.data[key]])) }) root_obj = None # Sometimes it's good enough just to save in reverse deletion order. if duplicate_order is None: duplicate_order = reversed(related_models) for model in duplicate_order: # Find all FKs on model that point to a related_model. fks = [] for f in model._meta.fields: if isinstance(f, ForeignKey) and f.rel.to in related_models: fks.append(f) # Replace each `sub_obj` with a duplicate. if model not in collector.data: continue sub_objects = collector.data[model] for obj in sub_objects: for fk in fks: fk_value = getattr(obj, "%s_id" % fk.name) # If this FK has been duplicated then point to the duplicate. fk_rel_to = data_snapshot[fk.rel.to] if fk_value in fk_rel_to: dupe_obj = fk_rel_to[fk_value] setattr(obj, fk.name, dupe_obj) # Duplicate the object and save it. obj.id = None if field is not None: setattr(obj, field, value) obj.save() if root_obj is None: root_obj = obj return root_obj
编辑:删除调试"打印"语句.