0

我需要为查询集中删除的每个对象批量创建历史记录。我已经正确编码了,我认为如下。

def bulk_delete_with_history(objects, model, batch_size=None, default_user=None, default_change_reason="", default_date=None):
    """
    The package `simple_history` logs the deletion one object at a time.  
    This does it in bulk.
    """
    model_manager = model._default_manager
    model_manager.filter(pk__in=[obj.pk for obj in objects]).delete()

    history_manager = get_history_manager_for_model(model)

    history_type = "-"
    historical_instances = []
    for instance in objects:
        history_user = getattr(
            instance,
            "_history_user",
            default_user or history_manager.model.get_default_history_user(
                instance),
        )
        row = history_manager.model(
            history_date=getattr(
                instance, "_history_date", default_date or timezone.now()
            ),
            history_user=history_user,
            history_change_reason=get_change_reason_from_object(
                instance) or default_change_reason,
            history_type=history_type,
            **{
                field.attname: getattr(instance, field.attname)
                for field in instance._meta.fields
                if field.name not in history_manager.model._history_excluded_fields
            }
        )
        if hasattr(history_manager.model, "history_relation"):
            row.history_relation_id = instance.pk
        historical_instances.append(row)

    return history_manager.bulk_create(
        historical_instances, batch_size=batch_size
    )

但问题是我需要断开 post_delete 信号,以便在我一次完成所有操作之前不会由简单的历史记录创建历史记录。

我已经尝试过了,但它不起作用。

models.signals.post_delete.disconnect(HistoricalRecords.post_delete, sender=Customer)

whereCustomer只是我用来测试此实用程序功能的一个类。

有人可以建议吗?提前致谢。

在他们的 github 页面上也问了这个问题 - https://github.com/jazzband/django-simple-history/issues/717

4

1 回答 1

0

我在断开信号时犯了一个典型的错误。当然,必须与已连接的对象断开连接。此处对此进行了更详细的讨论-django signal disconnect not working

这现在有效,因为我正在参考正确的对象断开连接。

        receiver_object = models.signals.post_delete._live_receivers(Customer)[0]
        models.signals.post_delete.disconnect(receiver_object, sender=Customer)

不过,我认为如果 django-simple-history 提供了一个 bulk_delete 实用程序函数,就像他们为 bulk_create 和 bulk_update 提供的一样,那会很好。

于 2020-09-27T19:28:34.490 回答