复制Django模型实例和所有指向I的外键

2024-04-25 20:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Django模型上创建一个方法,称之为model.duplicate(),它复制模型实例,包括指向它的所有外键。我知道你可以做到:

def duplicate(self):
   self.pk = None
   self.save()

……但这样一来,所有相关模型仍然指向旧实例。在

我不能简单地保存对原始对象的引用,因为self在方法执行期间所指的更改:

^{pr2}$

我可以尝试保存对相关对象的引用:

def duplicate(self):
    original_fkeys = self.fkeys.all()
    self.pk = None
    self.save()
    self.fkeys.add(*original_fkeys)

…但这会将它们从原始记录转移到新记录。我要把它们抄过来,指着新唱片。在

其他地方的一些答案(在我更新问题之前)建议使用Python的^{},我怀疑它适用于这个模型上的外键,而不是指向它的另一个模型上的外键。在

def duplicate(self):
    new_model = copy.deepcopy(self)
    new_model.pk = None
    new_model.save()

如果您这样做,new_model.fkeys.all()(按照我目前的命名方案)将是空的。在


Tags: 对象实例方法模型selfnonenewmodel
3条回答

虽然我接受了另一个发帖人的回答(因为它帮助我到达了这里),但我还是想把我最终得到的解决方案贴出来,以防它能帮助其他陷入同样困境的人。在

def duplicate(self):
    """
    Duplicate a model instance, making copies of all foreign keys pointing
    to it. This is an in-place method in the sense that the record the
    instance is pointing to will change once the method has run. The old
    record is still accessible but must be retrieved again from
    the database.
    """
    # I had a known set of related objects I wanted to carry over, so I
    # listed them explicitly rather than looping over obj._meta.fields
    fks_to_copy = list(self.fkeys_a.all()) + list(self.fkeys_b.all())

    # Now we can make the new record
    self.pk = None
    # Make any changes you like to the new instance here, then
    self.save()

    foreign_keys = {}
    for fk in fks_to_copy:
        fk.pk = None
        # Likewise make any changes to the related model here
        # However, we avoid calling fk.save() here to prevent
        # hitting the database once per iteration of this loop
        try:
            # Use fk.__class__ here to avoid hard-coding the class name
            foreign_keys[fk.__class__].append(fk)
        except KeyError:
            foreign_keys[fk.__class__] = [fk]

    # Now we can issue just two calls to bulk_create,
    # one for fkeys_a and one for fkeys_b
    for cls, list_of_fks in foreign_keys.items():
        cls.objects.bulk_create(list_of_fks)

使用时的外观:

^{pr2}$

为了保护无辜的人,模特和相关模特的名字都改了。在

您可以创建新实例并按如下方式保存它

def duplicate(self):
    kwargs = {}
    for field in self._meta.fields:
        kwargs[field.name] = getattr(self, field.name)
        # or self.__dict__[field.name]
    kwargs.pop('id')
    new_instance = self.__class__(**kwargs)
    new_instance.save()
    # now you have id for the new instance so you can
    # create related models in similar fashion
    fkeys_qs = self.fkeys.all()
    new_fkeys = []
    for fkey in fkey_qs:
        fkey_kwargs = {}
        for field in fkey._meta.fields:
            fkey_kwargs[field.name] = getattr(fkey, field.name)
        fkey_kwargs.pop('id')
        fkey_kwargs['foreign_key_field'] = new_instance.id
        new_fkeys.append(fkey_qs.model(**fkey_kwargs))
    fkeys_qs.model.objects.bulk_create(new_fkeys)
    return new_instance

我不确定它在很多领域会有什么表现。但对于简单的字段,它是有效的。对于新实例,您总是可以弹出您不感兴趣的字段。在

我迭代_元字段可以用copy完成,但重要的是使用新的id作为foreign_key_field。在

我确信通过编程可以检测出哪些字段是self.__class__foreign_key_field)的外键,但是由于可以有更多的字段,最好显式地命名一个(或多个)。在

我在Django 2.1/python3.6中尝试了其他答案,但它们似乎没有复制一对多和多对多相关对象(self._meta.fields不包含一对多相关字段,但self._meta.get_fields()有)。另外,其他答案要求事先知道相关字段名或要复制哪些外键。在

我编写了一种更通用的方法来实现这一点,处理一对多和多对多相关字段。包括评论,欢迎提出建议:

def duplicate_object(self):
    """
    Duplicate a model instance, making copies of all foreign keys pointing to it.
    There are 3 steps that need to occur in order:

        1.  Enumerate the related child objects and m2m relations, saving in lists/dicts
        2.  Copy the parent object per django docs (doesn't copy relations)
        3a. Copy the child objects, relating to the copied parent object
        3b. Re-create the m2m relations on the copied parent object

    """
    related_objects_to_copy = []
    relations_to_set = {}
    # Iterate through all the fields in the parent object looking for related fields
    for field in self._meta.get_fields():
        if field.one_to_many:
            # One to many fields are backward relationships where many child objects are related to the
            # parent (i.e. SelectedPhrases). Enumerate them and save a list so we can copy them after
            # duplicating our parent object.
            print(f'Found a one-to-many field: {field.name}')

            # 'field' is a ManyToOneRel which is not iterable, we need to get the object attribute itself
            related_object_manager = getattr(self, field.name)
            related_objects = list(related_object_manager.all())
            if related_objects:
                print(f' - {len(related_objects)} related objects to copy')
                related_objects_to_copy += related_objects

        elif field.many_to_one:
            # In testing so far, these relationships are preserved when the parent object is copied,
            # so they don't need to be copied separately.
            print(f'Found a many-to-one field: {field.name}')

        elif field.many_to_many:
            # Many to many fields are relationships where many parent objects can be related to many
            # child objects. Because of this the child objects don't need to be copied when we copy
            # the parent, we just need to re-create the relationship to them on the copied parent.
            print(f'Found a many-to-many field: {field.name}')
            related_object_manager = getattr(self, field.name)
            relations = list(related_object_manager.all())
            if relations:
                print(f' - {len(relations)} relations to set')
                relations_to_set[field.name] = relations

    # Duplicate the parent object
    self.pk = None
    self.save()
    print(f'Copied parent object ({str(self)})')

    # Copy the one-to-many child objects and relate them to the copied parent
    for related_object in related_objects_to_copy:
        # Iterate through the fields in the related object to find the one that relates to the
        # parent model (I feel like there might be an easier way to get at this).
        for related_object_field in related_object._meta.fields:
            if related_object_field.related_model == self.__class__:
                # If the related_model on this field matches the parent object's class, perform the
                # copy of the child object and set this field to the parent object, creating the
                # new child -> parent relationship.
                related_object.pk = None
                setattr(related_object, related_object_field.name, self)
                related_object.save()

                text = str(related_object)
                text = (text[:40] + '..') if len(text) > 40 else text
                print(f'|- Copied child object ({text})')

    # Set the many-to-many relations on the copied parent
    for field_name, relations in relations_to_set.items():
        # Get the field by name and set the relations, creating the new relationships
        field = getattr(self, field_name)
        field.set(relations)
        text_relations = []
        for relation in relations:
            text_relations.append(str(relation))
        print(f'|- Set {len(relations)} many-to-many relations on {field_name} {text_relations}')

    return self

相关问题 更多 >