django-simple-history在现有历史存在时填充历史

3bygqnnd  于 2023-03-31  发布在  Go
关注(0)|答案(2)|浏览(170)

在使用django-simple-history为模型设置了历史记录之后,我想运行populate_history来根据表的现有内容填充历史记录表。但是,其他用户已经进行了一些更改,导致历史记录表被部分填充。运行populate_history --auto只会导致消息Existing history found, skipping model
我希望保留现有的历史记录,但要为当前未存储在历史记录中的所有记录填充历史记录。是否有方法做到这一点?

vmdwslir

vmdwslir1#

最后我写了一个基于populate_history的修改过的脚本。它识别所有没有历史记录的对象,并将它们添加到历史表中。下面是一个简单的版本(没有批处理)。

from django.apps import apps

from simple_history.utils import get_history_manager_for_model, get_history_model_for_model

def populate_model_history(model):
  history = get_history_model_for_model(model)
  history_manager = get_history_manager_for_model(model)

  # Insert historical records for objects without existing history
  # NOTE: A better approach would be to do this in batches, as in populate_history.py
  for instance in model.objects.exclude(pk__in=history.objects.values_list(model._meta.pk.name)):
    history_manager.bulk_history_create([instance], batch_size=1)

model = apps.get_model('app', 'my_model')
populate_model_history(model)
sg3maiej

sg3maiej2#

受@beldaz和the tests in simple-history的启发,我简单地调用populate_history作为迁移操作

from io import StringIO
from django.conf import settings
from django.core import management
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
import uuid

def forwards(apps, _):
    # backfill history
    management.call_command(
        "populate_history", "invoicing.Payment", stdout=StringIO(), stderr=StringIO()
    )

class Migration(migrations.Migration):
    dependencies = [
        # <autofilled by simple history>
    ]

    operations = [
        # <autofilled by simple history>,
        migrations.RunPython(forwards)
    ]

相关问题