首页 > 解决方案 > Django MPTT:在迁移文件中重建树

问题描述

我的项目中已经有一个模型,现在我想与 django-mptt 一起使用。该模型中已经包含一些数据。

在迁移期间,系统会要求您为 django-mptt 创建的某些字段设置默认值。按照文档中的指示,我将 0 设置为一次性默认值。文档继续进行并建议Model.objects.rebuild()在完成此操作后运行以在字段中设置正确的值。我想通过我的迁移文件执行此操作。我不想通过我的 django-shell 运行它,因为这不是一次性操作。

我的迁移文件是这样的:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-12-27 17:33
from __future__ import unicode_literals

from django.db import migrations, models


def migrate_mptt(apps, schema_editor):
    ProductCategory = apps.get_model("product", "ProductCategory")
    ProductCategory.objects.rebuild()


class Migration(migrations.Migration):

    dependencies = [
        ('product', '0016_auto_20181227_2303'),
    ]

    operations = [
        migrations.RunPython(migrate_mptt),
    ]

在迁移时,我收到错误AttributeError: 'Manager' object has no attribute 'rebuild'。当然,相同的命令在 shell 中也能完美运行。

我需要通过迁移来做到这一点,因为我希望每次部署我的项目时自动运行此操作。

标签: djangodjango-mptt

解决方案


如果您想重建适当的迁移,您可以使用此代码。如果您AttributeError对此有所了解,请尝试将模型管理器设置为your_name属性(而不是objects)。

此外,如果您希望在迁移后重建,您可以扩展您的应用配置:

    from django.apps import AppConfig
    from django.db.models.signals import post_migrate

    def rebuild_tree(sender, **kwargs):
        from .models import YourModel
        YourModel.objects.rebuild()

    class YouApponfig(AppConfig):
        name = 'app_name'

        def ready(self):
            post_migrate.connect(rebuild_tree, sender=self)

推荐阅读